在 C++ 中对任意长度的类型列表进行模板化;

发布于 2024-08-22 16:49:41 字数 481 浏览 15 评论 0原文

这是我希望能够输入的内容:

class foo : public watchKeys<A, B, C> {}; //Or any list of keys

Boost::mpl 有序列,允许您执行此操作,但我不想必须这样做:

class foo : public watchKeys<mpl::list<A, B, C> > {};

我不介意它内部“丑陋”或冗长,但我希望 watchKeys 最终的使用方式非常简单直观。我也无法弄清楚 boost 是如何做到这一点的,但这似乎是因为我和模板之间有一层宏。

我该怎么办?我宁愿为每种数量的类型做巨大的模板列表,但如果这是唯一的,那就是唯一的方法......

编辑:我已经相当确定没有办法做我想做的事(几乎,但你不能有可变数量的宏参数),但问题仍然产生有用且信息丰富的答案。

Here's what I want to be able to type:

class foo : public watchKeys<A, B, C> {}; //Or any list of keys

Boost::mpl has sequences, which allow you to do this, but I don't want to have to do:

class foo : public watchKeys<mpl::list<A, B, C> > {};

I don't mind it being "ugly" or verbose on the inside, but I want the way watchKeys is ultimately used to be very simple and intuitive. I also can't figure out how boost is doing it, but that seems to be because there's a layer of macros between me and templates.

How might I go about this? I'd prefer not to do the giant list of templates for each number of types, but if that's the only it's the only way...

Edit: I've become fairly certain that there's no way to do what I want to do (almost, but you can't have a variable number of macro arguments), but the question is still generating useful and informative answers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

财迷小姐 2024-08-29 16:49:41

每种类型的巨大模板列表是当前版本的 C++ 中实现此目的的唯一方法。有关如何进行的示例,请参阅 boost::tuple。

C++0X 支持可变参数模板,但这还没有得到很好的支持(我认为现代版本的 GCC 虽然有实验性支持)。

The giant list of templates for each number of types is the only way to do it in the current version of C++. See boost::tuple for an example of how to go about.

C++0X supports variadic templates, but that isn't well supported yet (I think modern version of GCC have experimental support though).

海之角 2024-08-29 16:49:41

或者你可以递归地执行

template<typename Head, typename Tail>
struct list { };

struct emptylist { };

class foo : public watchKeys<list<A, 
                             list<B, 
                             list<C, emptylist> > > > { };

然后你可以像这样处理它

template<typename List>
struct process;

template<typename Head, typename Tail>
struct process< list<Head, Tail> > : process<Tail> { 
  // process Head
};

template<>
struct process<emptylist> { };

Alternatively you can do it recursively

template<typename Head, typename Tail>
struct list { };

struct emptylist { };

class foo : public watchKeys<list<A, 
                             list<B, 
                             list<C, emptylist> > > > { };

You can then process it like this

template<typename List>
struct process;

template<typename Head, typename Tail>
struct process< list<Head, Tail> > : process<Tail> { 
  // process Head
};

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