使用`std :: enable_if <std :: is_compound <double> :: value>的意外SFINAE行为

Mar*_*sen 2 c++ c++11

我有一个模板化的类,我想根据模板参数启用不同的构造函数.具体来说,我想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
}
Run Code Online (Sandbox Code Playgroud)

我收到以下编译错误:

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
Run Code Online (Sandbox Code Playgroud)

coliru

问题似乎是正在使用构造函数的第一个版本,因为double::value_type不存在而失败.问题是该构造函数不应该Foo<double>首先出现,因为std::is_compound<double>::valuefalse.

为什么std::enable_if似乎不能正常工作?

R. *_*des 5

typename T::value_type&,T不能替代double.由于T是类模板的模板参数而不是构造函数模板的模板参数,因此无法通过替换失败来排除过载.SFINAE仅在涉及所涉及模板的参数时才有效.

如果使用typename U::value_type&,则会得到替换失败,这不是错误,因为它U是构造函数模板的参数,而不是类模板的参数.