将 SFINAE 用于模板化构造函数时遇到问题
trouble using SFINAE for templated constructor
下面2个有什么区别:
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
explicit Approx(const T& value) {}
对
template <typename T>
explicit Approx(const typename std::enable_if<std::is_constructible<double, T>::value, T>::type& value) {}
Approx
是普通 class(未模板化)的构造函数,我需要 double
可从
构造的类型
我的问题是第一个有效,但不是 C++98(默认模板参数等 - 我有自己的 enable_if
和 is_constructible
的 c++98 特性)
我问的原因是因为我想支持 double
:
的强类型定义
class Volatility {
double underlying_;
public:
explicit Volatility(double u) : underlying_(u) {}
explicit operator double() const { return underlying_; }
};
Approx(Volatility(1.)); // error
你的 C++03 版本不工作,因为它不能推导 T,给定参数。构造函数的常用 C++03 机制是一个额外的默认参数。
template<typename T>
explicit Approx(const T& value, typename std::enable_if<std::is_constructible<double, T>::value>::type* dummy = 0) {}
T
在这种形式下是可推导的,如果 T
满足 enable_if
指定的期望,额外的参数最终是 void*
。
下面2个有什么区别:
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
explicit Approx(const T& value) {}
对
template <typename T>
explicit Approx(const typename std::enable_if<std::is_constructible<double, T>::value, T>::type& value) {}
Approx
是普通 class(未模板化)的构造函数,我需要 double
可从
我的问题是第一个有效,但不是 C++98(默认模板参数等 - 我有自己的 enable_if
和 is_constructible
的 c++98 特性)
我问的原因是因为我想支持 double
:
class Volatility {
double underlying_;
public:
explicit Volatility(double u) : underlying_(u) {}
explicit operator double() const { return underlying_; }
};
Approx(Volatility(1.)); // error
你的 C++03 版本不工作,因为它不能推导 T,给定参数。构造函数的常用 C++03 机制是一个额外的默认参数。
template<typename T>
explicit Approx(const T& value, typename std::enable_if<std::is_constructible<double, T>::value>::type* dummy = 0) {}
T
在这种形式下是可推导的,如果 T
满足 enable_if
指定的期望,额外的参数最终是 void*
。