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



// 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:


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).



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) {}

转载请明显位置注明出处:c – 构造函数有条件地标记为显式