使用表达式参数专门化模板

Neg*_*ero 3 c++ templates

我有一个这样的课:

template <class T>
class Foo;
Run Code Online (Sandbox Code Playgroud)

我想要专业化

template <>
class Foo < size_t N >;
Run Code Online (Sandbox Code Playgroud)

但那并不适合我:

我的主要是:

Foo<int> p;  // OK
Foo<15> p2;  // fails to compile
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Ker*_* SB 5

您不能 - 您的模板始终采用一个类型参数.专业化只能比这更特殊,但没有不同(因此名称).

也许你可以使用辅助模板来存储价值信息:

template <typename T, T Val> struct ValueWrapper { };

template <typename T> struct Foo;

templaet <typename T, T Val> struct Foo<ValueWrapper<T, Val>>
{
    typedef T type;
    static type const value = Val;

    // ...
};
Run Code Online (Sandbox Code Playgroud)

用法:

Foo<char> x;
Foo<ValueWrapper<int, 15>> y;
Run Code Online (Sandbox Code Playgroud)

  • [`std :: integral_constant`](http://en.cppreference.com/w/cpp/types/integral_constant)怎么样? (2认同)