c++ - 如何编写可以专门用于对象或 int N 的模板

标签 c++ templates c++11 c++14

我想要实现的是一个带有“灵活”第一个参数的模板(这很可能类似于数组元素,与 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>

Live on Coliru

关于c++ - 如何编写可以专门用于对象或 int N 的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37880964/

相关文章:

c++ - 使用 boost.pool 而不是 'new' 作为对象容器

c++ - 通过派生模板类的正确类型转换从基类访问数据

c++ - 如何使用模板查找最多的多个数字?

c++ - 在运行前对字符串进行操作

c++ - 无法 emplace_back 具有 const 成员的类的实例

c++ - 为什么我们需要 C++ 中的虚函数?

c++ - 我的 C++ 程序不会从命令行读取多个文件

c++ - 为什么在使用 std::remove() 从 vector 中删除多个值时会发生跳过?

c++ - 比较键和值 std::maps

c++ - 如何在不越过缓冲区的情况下将字符串复制到 C++ 中的 char 数组中