11

这是场景:我想要一个可以有可变数量的 mixin 的主机类(使用可变参数模板不太难——例如参见http://citeseerx.ist.psu.edu/viewdoc/summary?doi =10.1.1.103.144)。但是,我还希望由宿主类对 mixin 进行参数化,以便它们可以引用其公共类型(使用 CRTP 习惯用法)。尝试混合两者时会出现问题——我不清楚正确的语法。例如,以下代码使用 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 混合的成功经验?

4

1 回答 1

8

以下似乎有效。我添加Mixins...了继承的 mixin 类,它就地扩展了参数包。在模板主体之外,必须指定Host所有模板参数,以便达到目的。在正文中,无需拼出所有模板参数就足够了。有点短手。HostMixins...Host

#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>());
}
于 2010-03-17T15:31:45.900 回答