enable_if和构造函数

时间:2012-07-07 13:57:41

标签: boost enable-if

这有什么不对吗?

我认为在使用enable if ???

时这应该可行

帮助??

不应排除第二个构造函数吗?

#include <iostream>
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>



template<class T>
class integral_holder{
public:
integral_holder(T value_, typename boost::enable_if_c< boost::is_integral<T>::value>::type* ignore = 0) : value(value_){
    std::cout << "Integral" << std::endl;
}

integral_holder(T value_, typename boost::enable_if_c< boost::is_floating_point<T>::value>::type* ignore = 0) : value(floor(value_)){
    std::cout << "Floating point" << std::endl;
}

private:
  T value;

};

int main(int argc, const char * argv[])
{

   integral_holder<int> a(22);

   return 0;
}

1 个答案:

答案 0 :(得分:4)

当从类模板生成类并且在该进程中实例化构造函数的声明(不是它们的主体,而只是它们的“签名”)时,enable_if类型无效并且您得到编译器错误。

您需要使enable_if类型取决于构造函数的模板参数(使其成为函数模板)。那么你的目标是有效的,因为当你使用会触发SFINAE案例的构造函数时,在推导函数模板参数类型时会形成无效类型。