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++ - 使用命令行选项包含头文件?

c++ - std::string 插入方法有不明确的重载?

javascript - 改变 React 渲染结构的最佳方法

c++ - 为什么在析构函数中抛出异常时不调用重载删除?

c++ - 在 C++ 中管理内存所有权的最佳方式?共享指针或其他机制?

c++ - 为什么在 C++11 中的类型参数包之后不允许使用整数值参数包?

c++ - 自动模板推导中的常量正确性

用于获取函数参数数量的 C++ 模板机制,适用于 lambda 和普通函数

c++ - std::uniform_int_distribution 放入函数中还是我用错了?

c++ - 获取文件数据后刷新 cout 的问题