【发布时间】:2009-10-20 21:41:34
【问题描述】:
我有一个类,我希望它的功能依赖于一组插件策略。但是,我不确定如何让一个类派生自任意数量的类。
下面的代码是我想要实现的示例。
// insert clever boost or template trickery here
template< class ListOfPolicies >
class CMyClass : public ListOfPolicies
{
public:
CMyClass()
{
// identifiers should be the result of OR-ing all
// of the MY_IDENTIFIERS in the TypeList.
DWORD identifiers;
DoSomeInitialization( ..., identifiers, ... );
}
int MyFunction()
{
return 100;
}
// ...
};
template< class T >
class PolicyA
{
public:
enum { MY_IDENTIFIER = 0x00000001 };
int DoSomethingA()
{
T* pT = static_cast< T* >( this );
return pT->MyFunction() + 1;
};
// ...
};
template< class T >
class PolicyB
{
public:
enum { MY_IDENTIFIER = 0x00000010 };
int DoSomethingB()
{
T* pT = static_cast< T* >( this );
return pT->MyFunction() + 2;
};
// ...
};
int _tmain(int argc, _TCHAR* argv[])
{
CMyClass< PolicyA > A;
assert( A.DoSomethingA() == 101 );
CMyClass< PolicyA, PolicyB > AB
assert( AB.DoSomethingA() == 101 );
assert( AB.DoSomethingB() == 102 );
return 0;
}
谢谢, 保罗H
【问题讨论】:
-
为什么你的示例方法不起作用?
-
它可能会起作用。我只是不知道如何实现我提到的部分。
-
如果听起来您正在重新实现 COM 的功能。为什么不使用 COM?
-
哦,你在找什么我认为是可变参数模板,在 C++0X 中引入
-
@Jherico 我在 COM 中涉猎过一点,但我想不出其中有什么可以实现这一点。你能举个有用的例子吗?
标签: c++ templates multiple-inheritance