【发布时间】:2015-03-12 16:04:33
【问题描述】:
我想专门化一个模板类构造函数:
如果类型是int,默认值是50和-50。如果它是浮动默认值应该是 0.5 和 -0.5 。
我的代码是:
#include <iostream>
#include <limits>
#include <type_traits>
template<typename T>
class Foo{
public:
template<typename = typename std::enable_if<
std::is_integral<T>::value&& !std::is_floating_point<T>::value>::type>
Foo(T value1 = 50, T value2 = -50) :value1_(value1), value2_(value2){}
template<typename = typename std::enable_if<
std::is_floating_point<T>::value>::type>
Foo(T value1 = 0.5, T value2 = -0.5, void* dummy = 0) : value1_(value1), value2_(value2){}
T value1_, value2_;
};
int main()
{
Foo<float> test;
std::cout << test.value1_ << " " << test.value2_ << '\n';
Foo<int> test2;
std::cout << test2.value1_ << " " << test2.value2_;
}
它 works just fine 在 Visual Studio 2013 中。
main.cpp: In instantiation of 'class Foo<float>':
main.cpp:29:13: required from here
main.cpp:19:3: error: no type named 'type' in 'struct std::enable_if<false, void>'
Foo(T value1 = 50, T value2 = -50) :value1_(value1), value2_(value2){}
^
main.cpp: In instantiation of 'class Foo<int>':
main.cpp:32:11: required from here
main.cpp:23:3: error: no type named 'type' in 'struct std::enable_if<false, void>'
Foo(T value1 = 0.5, T value2 = -0.5, void* dummy = 0) : value1_(value1), value2_(value2){}
^
我的代码错了吗?如果是这样,为什么 Visual Studio 编译它?或者可能是 gcc 错误?!
【问题讨论】:
-
与您的问题无关,但如果您使用的是
std::is_integral,为什么不能使用标准std::is_floating_pointtype-trait?
标签: c++ class templates c++11 sfinae