C ++中的Mixins,可变参数模板和CRTP [英] Mixins, variadic templates, and CRTP in C++

查看:102
本文介绍了C ++中的Mixins,可变参数模板和CRTP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下:我想拥有一个主机类,该主机类可以具有可变数量的mixins(对于可变参数模板来说不太难,请参见例如

Here's the scenario: I'd like to have a host class that can have a variable number of mixins (not too hard with variadic templates--see for example http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.103.144). However, I'd also like the mixins to be parameterized by the host class, so that they can refer to its public types (using the CRTP idiom). The problem arises when trying to mix the two--the correct syntax is unclear to me. For example, the following code fails to compile with g++ 4.4.1:

template <template<class> class... Mixins>
class Host : public Mixins<Host<Mixins>>... {
  public:
    template <class... Args>
    Host(Args&&... args) : Mixins<Host>(std::forward<Args>(args))... {}
};

template <class Host> struct Mix1 {};

template <class Host> struct Mix2 {};

typedef Host<Mix1, Mix2> TopHost;
TopHost *th = new TopHost(Mix1<TopHost>(), Mix2<TopHost>());

出现错误:

tst.cpp: In constructor ‘Host<Mixins>::Host(Args&& ...) [with Args = Mix1<Host<Mix1, Mix2> >, Mix2<Host<Mix1, Mix2> >, Mixins = Mix1, Mix2]’:

tst.cpp:33:   instantiated from here

tst.cpp:18: error: type ‘Mix1<Host<Mix1, Mix2> >’ is not a direct base of ‘Host<Mix1, Mix2>’

tst.cpp:18: error: type ‘Mix2<Host<Mix1, Mix2> >’ is not a direct base of ‘Host<Mix1, Mix2>’

有人成功将可变参数模板与CRTP混合使用吗?

Does anyone have successful experience mixing variadic templates with CRTP?

推荐答案

以下似乎有效.我在继承的mixin类中添加了Mixins...,从而扩展了参数包的位置.在Host模板的主体之外,必须指定Host的所有模板参数,以便Mixins...达到目的.在体内,仅Host就足够了,无需拼写其所有模板参数.有点空手.

The following seems to work. I added Mixins... in the inherited mixin classes which expands the parameter pack inplace. Outside the body of Host template, all template parameters of Host must be specified so Mixins... serves the purpose. Inside the body, just Host is sufficient no need to spell out all its template parameters. Kind of a short hand.

#include <utility>

template <template<class> class... Mixins>
class Host : public Mixins<Host<Mixins...>>...
{
  public:
    Host(Mixins<Host>&&... args) : Mixins<Host>(std::forward<Mixins<Host>>(args))... {}
};

template <class Host> struct Mix1 {};
template <class Host> struct Mix2 {};

int main (void)
{
  typedef Host<Mix1, Mix2> TopHost;
  delete new TopHost(Mix1<TopHost>(), Mix2<TopHost>());
}

这篇关于C ++中的Mixins,可变参数模板和CRTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆