C ++ 11中的可变参数模板和多重继承 [英] Variadic templates and multiple inheritance in c++11
问题描述
我正在尝试实现以下目标:
i'm trying to achieve something like this:
我有一个要动态继承的模板化基类
I have a templated base class which i want to inherit dynamically
template<typename A, typename B>
class fooBase
{
public:
fooBase(){};
~fooBase(){};
};
所需方法:(类似这样,不确定如何做到)
desired method: (something like this, not really sure how to do it)
template <typename... Interfaces>
class foo : public Interfaces...
{
public:
foo();
~foo();
}
我的目标是让foo类的行为如下:
and my goal is to have the foo class act like this:
第二种方法:
class foo()
: public fooBase<uint8_t, float>
, public fooBase<uint16_t, bool>
, public fooBase<uint32_t, int>
// and the list could go on
{
foo();
~foo();
}
使用第二种方法的问题是,如果我实例化一个foo对象,它将将会一直继承这3个基类,我想使其更通用,并且在实例化foo对象时,使用可变参数模板为它提供基类的参数,以便我可以将foo类用于其他类型(也许继承仅一个基类,可能是五个)
with the second method the problem is that if i instantiate an foo object, it will inherit all the time those 3 base classes, i want to make it more generally and when instantiate a foo object, give it with variadic templates the parameters for the base classes, so that i can use the foo class for other types(maybe will inherit just one base class, maybe five)
谢谢
实例化foo的示例
foo<<uint8_t, float>, <uint16_t, bool>, <uint32_t, int>, /* and the list could go on and on */> instance
推荐答案
您可以尝试使用2个参数的递归可变参数模板
You could try recursive variadic templates, taking 2 arguments at a time to add a derivation from fooBase.
可能是这样的:
template<typename A, typename B>
class fooBase
{
public:
fooBase(){};
~fooBase(){};
};
template<typename A, typename B, typename ... C>
class foo: public fooBase<A, B>, public foo<C ...> {
};
// termination version by partial specialization
template<typename A, typename B>
class foo<A, B>: public fooBase<A, B> {
};
然后可以声明:
foo<uint8_t, float, uint16_t, bool, uint32_t, int> bar;
,bar将是 fooBase< uint8_t,float> 的子对象code>,
fooBase< uint16_t,bool>
和 fooBase< uint32_t,int>
and bar will be a subobject of fooBase<uint8_t, float>
, fooBase<uint16_t, bool>
and fooBase<uint32_t, int>
这篇关于C ++ 11中的可变参数模板和多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!