c – 构造函数有条件地标记为显式

cppreference std::tuple constructor page有一堆C 17音符说:

This constructor is explicit if and only if std::is_convertible<const Ti&, Ti>::value is false for at least one i

如何写一个有条件的构造函数?想到的第一个可能性是明确的(true),但这不是合法的语法。

与enable_if的尝试失败:

// constructor is explicit if T is not integral
struct S {
  template <typename T,
            typename = typename std::enable_if<std::is_integral<T>::value>::type>
  S(T) {}

  template <typename T,
            typename = typename std::enable_if<!std::is_integral<T>::value>::type>
  explicit S(T) {}
};

与错误:

error: ‘template<class T, class> S::S(T)’ cannot be overloaded
explicit S(T t) {}
增加N4387: Improving pair and tuple, revision 3的建议有一个如何工作的例子:

Consider the following class template A that is intended to be used
as a wrapper for some other type T:

06000

The shown constructors both use perfect forwarding and they have
essentially the same signatures except for one being explicit, the
other one not. Furthermore, they are mutually exclusively constrained.
In other words: This combination behaves for any destination type T
and any argument type U like a single constructor that is either
explicit or non-explicit (or no constructor at all).

据Praetorian指出,这正是070​​01。

如果我们相应地修改OPs示例,它也可以:

struct S {
  template <typename T,
             typename std::enable_if<std::is_integral<T>::value, bool>::type = false >
  S(T) {}

  template <typename T,
            typename std::enable_if<!std::is_integral<T>::value, bool>::type = false>
  explicit S(T) {}
};
http://stackoverflow.com/questions/32998807/constructor-conditionally-marked-explicit

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c – 构造函数有条件地标记为显式