gpt4 book ai didi

c++ - 从任意数量的类派生

转载 作者:太空狗 更新时间:2023-10-29 23:42:57 25 4
gpt4 key购买 nike

我有一个类,我希望其功能依赖于一组插件策略。但是,我不确定如何让一个类派生自任意数量的类。

下面的代码是我正在努力实现的示例。

// 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

最佳答案

随着Boost.MPL图书馆:

//Warning: Untested
namespace bmpl = boost::mpl;
template<class Typelist>
class X : bmpl::inherit_linearly<Typelist, bmpl::inherit<bmpl::_1, bmpl::_2> >::type
{
...
};

用作:

X<bmpl::vector<Foo, Bar, Baz> > FooBarBaz;

对于“OR-ing all MY_IDENTIFIER”部分,遵循以下内容:

//Warning: still not tested:
enum {OR_ED_IDENTIFIERS =
bmpl::fold<Typelist, bmpl::int_<0>, bmpl::bitor_<_1, _2> >::value;
}

关于c++ - 从任意数量的类派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1597503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com