具有可变数量类型的模板
我想编写一个这样的 C++ 模板:
template <class Type1, class Type2, class Type3,....>
class MyClass
{
//...
};
但是,“类型数量”是可变的。
例如,用户可以创建具有 3 种类型的对象:
MyClass<int, int, int> obj;
或者他可以创建具有 5 种类型的对象:
MyClass<int, int, int, int, int> obj;
换句话说,我想要用户:
1.标明字段数量。
2.根据字段数量设置类型。
我怎么能这样做呢?
提前致谢。
I want to write a C++ template like this:
template <class Type1, class Type2, class Type3,....>
class MyClass
{
//...
};
But, "the number of types" is variable.
For example, a user can create an object with 3 types:
MyClass<int, int, int> obj;
or he can create an object with 5 types:
MyClass<int, int, int, int, int> obj;
In other words, I want the user :
1.Indicate the number of fields.
2.Set the types according to the number of fields.
how could I do this?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可变参数模板。 C++0x :(
只是提一下,您可以在当前的 C++ 中解决这个问题。例如,您可以看一下
Boost::tuple
:您不能分配可变元组的类型数量,
boost::tuple
最多允许您使用10种类型litb 在之前的答案中展示了如何做到这一点,但我找不到它。Variadic templates. C++0x :(
Just to mention that you can get around that in current C++. For example, you can take a look at
Boost::tuple
:You can't assign a variable number of types to the tuple,
boost::tuple
allows you up to 10 types only. I think litb showed how to do that in a previous answer but I couldn't find it.我认为你应该看看 Alexandrescu 的书现代 C++ 设计。关于类型列表的第 3 章似乎非常接近您想要的内容。
I think you should take a look at Alexandrescu's book Modern C++ Design. Chapter 3 on typelists seems to be pretty near to what you want.
据我所知,目前唯一的解决方案是为每种情况编写一个单独的模板。在某些情况下,您可能可以使用枚举来输入映射或类型列表,但我们需要首先了解您想要对类型执行的操作。
as far as I know the only solution right now is to write a separate template for each case. in some cases you might be able to use an enum to type map or a type list, but we would need to know more about what you want to do with the types first.
您所做的就是编写该模板,以便它需要足够多的参数,但为所有参数提供默认参数。然后,您使用模板元编程来筛选参数并清除默认参数。
听取 Neils 的建议并购买 MC++D。这就是我们大多数人学习这项技术的方式。
What you do is your write that template so that it takes a big enough number of arguments, but give default ones to all of them. Then you use template-meta programming to sift through the arguments and weed out the default ones.
Take Neils advice and buy MC++D. That's how most of us learned this technique.