我有一个模板类,我想根据模板参数启用不同的构造函数。具体来说,我想以此std::is_compound
为标准。
SSCCE
// bla.cpp
#include <type_traits>
#include <vector>
template <typename T>
class Foo{
double bar;
public:
template<typename U=T,
class = typename std::enable_if<std::is_compound<U>::value>::type
>
Foo(typename T::value_type& b):bar(b){}
template<typename U=T,
class = typename std::enable_if<!std::is_compound<U>::value>::type
>
Foo(T b):bar(b){}
};
int main(){
double d=1.0;
Foo<std::vector<double>> f2(d); // works
Foo<double> f1(d); // compiler error
}
我收到以下编译错误:
g++ -std=gnu++11 bla.cpp
bla.cpp: In instantiation of ‘class
Foo<double>’: bla.cpp:22:18: required from here bla.cpp:11:2: error:
‘double’ is not a class, struct, or union type
问题似乎是正在使用构造函数的第一个版本,由于double::value_type
不存在而失败。问题是构造函数不应该Foo<double>
放在首位,因为std::is_compound<double>::value
is false
.
为什么std::enable_if
似乎无法正常工作?