【问题标题】:trouble using SFINAE for templated constructor将 SFINAE 用于模板化构造函数时遇到问题
【发布时间】:2017-04-09 12:47:32
【问题描述】:

以下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++ templates sfinae c++03 c++98


    【解决方案1】:

    你的 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*

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      相关资源
      最近更新 更多