Eit*_*tan 11 g++ variadic mixins crtp c++11
这是一个场景:我想拥有一个可以拥有可变数量的mixins的宿主类(对于可变参数模板来说并不太难 - 请参阅http://citeseerx.ist.psu.edu/viewdoc/summary?doi = 10.1.1.103.144).但是,我也喜欢使用主机类参数化mixins,以便它们可以引用其公共类型(使用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>());
Run Code Online (Sandbox Code Playgroud)
有错误:
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>’
Run Code Online (Sandbox Code Playgroud)
有没有人成功地将可变参数模板与CRTP混合?
以下似乎有效.我Mixins...
在继承的mixin类中添加了扩展参数包的地方.在Host
模板体外,Host
必须指定所有模板参数,以Mixins...
达到目的.在身体内部,只需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>());
}
Run Code Online (Sandbox Code Playgroud)