std :: enable_if在Visual Studio 2013中无法正常工作

Tho*_*ell 1 c++ templates enable-if template-meta-programming c++11

我正在用C++编写一个小型库,我只想在模拟算术类型的情况下实例化模板,我发现了以下问题:

如果我有以下定义Foo:

template<typename T, typename Enable = void>
class Foo;

template<typename T>
class Foo<T, std::enable_if<std::is_arithmetic<T>::value>::type> {
    Foo() = default;
    Foo( const Foo& ) = default;
    ~Foo() = default;

    template<typename U>
    Foo( std::initializer_list<U> list )
    {
        static_assert(std::is_convertible<U, T>::value, "Must use an initializer list with type convertible to T");

        for( std::size_t s = 0; s < 10; ++s )
        {
            tArray[s] = static_cast<U>(list[s]);
        }
    }

private:
    T       tArray[10];
};
Run Code Online (Sandbox Code Playgroud)

我尝试按如下方式初始化它:

int main()
{
    Foo<int> test{ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} };

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Foo<T, std::enable_if<std::is_arithmetic<T>::value>::type>::Foo( std::initializer_list<U> )[with T=int,U=int]无法访问

我是新手std::enable_if在TMP中使用,但根据cppreference.com,它似乎应该可行.我在这里错过了什么,或者这是VS2013的错误?

Unu*_*sed 5

您的初始化程序被声明为私有.将其声明为公开.并且不要忘记typename在使用时添加std::enable_if<>::type.

编辑:没有下标重载std::initializer_list.

template<typename T, typename Enable = void>
class Foo;

template<typename T>
class Foo<T, typename std::enable_if<std::is_arithmetic<T>::value>::type> {

public:
    Foo() = default;
    Foo( const Foo& ) = default;
    ~Foo() = default;

    template<typename U>
    Foo( std::initializer_list<U> list )
    {
        static_assert(std::is_convertible<U, T>::value, "Must use an initializer list with type convertible to T");

        for( std::size_t s = 0; s < 10; ++s )
        {
            // ERROR
            // tArray[s] = static_cast<U>(list[s]);
        }
    }

private:
    T       tArray[10];
};
Run Code Online (Sandbox Code Playgroud)