如何编写一个可以使用对象或int n的模板
How to write a template that could be specialised with an object or an int N
我要实现的目标是一个模板,具有"灵活"的第一个参数(这很可能像数组元素,与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
相关文章:
- 在c++中访问int到类对象的映射时出错
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 包装一个对象并假装它是一个 int
- 类型为 'std::map< char,int > 的 <Swig 对象的代理
- 返回对象时从'const DList<int>* const'到 'DList<int>*' [-fallowive] 的转换无效
- 类对象在 int main() 中'undefined'
- 如果类对象需要在 C++ 中转换为 int,为什么会调用 "operator bool()"?
- 为什么 int 对象和函数类型之间不明确?
- switch 语句和对象隐式 int 转换
- 如何从 pair<int、对象的向量中删除重复项>
- 对类似"struct {double, int}"对象使用reinterpret_cast进行对象访问
- 重载 + 运算符以使用 int 添加对象
- 如何在C 2D向量中找到对象(而不是int)的位置
- 如何掩盖对象数组的数据类型字符串到C 中的INT
- jfieldid int对对象无效
- 在 c++ 中声明 int 对象
- 根据C++标准,int 变量是对象吗?
- 过载int 对象C 如何
- PyQt5:使用自定义信号时 int 对象的错误转换
- 字符串和 int 对象或左值/右值的内存位置