将 SFINAE 用于模板化构造函数时出现问题

trouble using SFINAE for templated constructor

本文关键字:问题 构造函数 SFINAE 用于      更新时间:2023-10-16

以下 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是普通类(非模板化(的构造函数,我需要double可以从中构造

的类型

我的问题是第一个有效,但不是 C++98(默认模板参数等 - 我有自己的 enable_ifis_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*