如何编写一个可以使用对象或int n的模板

How to write a template that could be specialised with an object or an int N

本文关键字:int 对象 可以使 何编写 一个      更新时间:2023-10-16

我要实现的目标是一个模板,具有"灵活"的第一个参数(这很可能像数组元素,与std::vector的第一个参数不同)和第二个争论。对于第二个参数,我想要对数字的情况(例如std::array中的大小参数)或一般类的专业化。

对于类Foo,我目前有

template <typename T, template <typename> typename Y > class Foo{};

这样做的原因是我想我可以写专业:

template<typename T> class Foo<T, int N>{};

,给定一个struct Bar{}

template<typename T> class Foo<T, Bar>{};

但是编译器(C 11,ideOne.com)在使用规范的行上输出错误" error: template argument 2 is invalid"。

大概我已经错误地形成了无专业的声明。还是这甚至可能?

您可以使用辅助模板包裹整数并将其变成类型。这是例如boost.mpl。

使用的方法
#include <iostream>
template <int N>
struct int_ { }; // Wrapper
template <class> // General template for types
struct Foo { static constexpr char const *str = "Foo<T>"; };
template <int N> // Specialization for wrapped ints
struct Foo<int_<N>> { static constexpr char const *str = "Foo<N>"; };
template <int N> // Type alias to make the int version easier to use
using FooI = Foo<int_<N>>;
struct Bar { };
int main() {
    std::cout << Foo<Bar>::str << 'n' << FooI<42>::str << 'n';
}

输出:

 foo&lt; t&gt;foo&lt; n&gt; 

生活在coliru