我想要实现的是一个带有“灵活”第一个参数的模板(这很可能类似于数组元素,与 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
”。
大概是我错误地形成了 unspecialised 声明。或者这甚至可能吗?
最佳答案
您可以使用辅助模板来包装您的整数并将其转换为类型。这是例如 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<T> Foo<N>
关于c++ - 如何编写可以专门用于对象或 int N 的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37880964/