具有可变数量类型的模板

发布于 2024-08-02 04:39:28 字数 447 浏览 4 评论 0原文

我想编写一个这样的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

佼人 2024-08-09 04:39:28

可变参数模板。 C++0x :(

只是提一下,您可以在当前的 C++ 中解决这个问题。例如,您可以看一下 Boost::tuple

#include <boost/tuple/tuple.hpp>

int main()
{
    boost::tuple<int, double> tuple1(4, 2.0);
    boost::tuple<int, double, double> tuple2(16, 4.0, 2.0);
}

您不能分配可变元组的类型数量,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:

#include <boost/tuple/tuple.hpp>

int main()
{
    boost::tuple<int, double> tuple1(4, 2.0);
    boost::tuple<int, double, double> tuple2(16, 4.0, 2.0);
}

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.

烦人精 2024-08-09 04:39:28

我认为你应该看看 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.

半葬歌 2024-08-09 04:39:28

据我所知,目前唯一的解决方案是为每种情况编写一个单独的模板。在某些情况下,您可能可以使用枚举来输入映射或类型列表,但我们需要首先了解您想要对类型执行的操作。

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.

凯凯我们等你回来 2024-08-09 04:39:28

您所做的就是编写该模板,以便它需要足够多的参数,但为所有参数提供默认参数。然后,您使用模板元编程来筛选参数并清除默认参数。

听取 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文