更新: 条件显式已进入 C++20 草案。更多关于 cppreference
cppreference std::tuple 构造函数页面有一堆 C++17 注释,内容如下:
此构造函数是
explicit
当且仅当std::is_convertible<const Ti&, Ti>::value
对于至少一个为假i
如何编写一个有条件显式的构造函数?想到的第一个可能性是explicit(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) {}