C++11 如何使用SFINAE启用转换运算符的显式性的隐式性?
考虑以下代码:C++11 如何使用SFINAE启用转换运算符的显式性的隐式性?,c++11,implicit-conversion,sfinae,explicit,conversion-operator,C++11,Implicit Conversion,Sfinae,Explicit,Conversion Operator,考虑以下代码: // Preamble #include <iostream> #include <type_traits> // Wrapper template <class From> struct wrapper { // Implicit conversion template <class To, class = typename std::enable_if< std::is_convertible&
// Preamble
#include <iostream>
#include <type_traits>
// Wrapper
template <class From>
struct wrapper
{
// Implicit conversion
template <class To, class = typename std::enable_if<
std::is_convertible<From, To>::value
>::type>
constexpr operator To() const noexcept;
// Explicit conversion
template <class To, class = typename std::enable_if<
!std::is_convertible<From, To>::value
&& std::is_constructible<To, From>::value
>::type>
explicit constexpr operator To() const noexcept;
};
// Main
int main(int argc, char* argv[])
{
wrapper<int> x;
double y = x;
return 0;
}
是的,只需将您的
class=typename std::enable_if::type
模式替换为typename std::enable_if::type=0
。然后,SFINAE参数是不同类型的非类型模板参数,函数会正确重载
// Preamble
#include <iostream>
#include <type_traits>
// Wrapper
template <class From>
struct wrapper
{
// Implicit conversion
template <class To, typename std::enable_if<
std::is_convertible<From, To>::value,
int>::type = 0>
constexpr operator To() const noexcept(noexcept(From{})) {
return From{};
}
// Explicit conversion
template <class To, typename std::enable_if<
!std::is_convertible<From, To>::value
&& std::is_constructible<To, From>::value,
int>::type = 0>
explicit constexpr operator To() const noexcept(noexcept(From{})) {
return From{};
}
};
// Main
int main(int argc, char* argv[])
{
wrapper<int> x;
double y = x;
return 0;
}