多方面模板类专业化

Multiple aspects template class specialization

本文关键字:专业化 多方面      更新时间:2023-10-16

>上下文

我目前正在用C++编写一些面向方面的代码。我有以下类层次结构:

class Base                   { virtual void doSmth() {/* generic stuff */ } };
class DerivedA : public Base { virtual void doSmth() {/* specific DerivedA stuff */} };
class DerivedB : public Base { virtual void doSmth() {/* specific DerivedB stuff */} };

我已经定义了一些方面类来为上述类添加一些功能:

template <class I>
class Aspect1 : public I
{
  void doSmth() { I::doSmth(); doSmthMore(); }
  void doSmthMore() { /* do something specific to Aspect1 */ }
};

template <class I>
class Aspect2 : public I
{
  void doSmth() { I::doSmth(); doSmthMore(); }
  void doSmthMore() { /* do something specific to Aspect2 */ }
};

在特定情况下(Aspect1超过DerivedADerivedB(,我有以下Aspect1专长:

template <>
class Aspect1< DerivedA > : public DerivedA
{
  void doSmth() { I::doSmth(); doSmthMore(); doSmthMoreA(); }
  void doSmthMore()  { /* do something specific to Aspect1 */ }
  void doSmthMoreA() { /* do something specific to Aspect1 for DerivedA*/ }
};
// Idem for Aspect1//DerivedB

我的问题

如何确保即使我以Aspect2<DerivedA>作为模板参数键入它,也会编译Aspect1的专用化,比如说DerivedA

即在配置文件中:

typedef Aspect2<Aspect1<DerivedA> > > ClassToBeUsed; // This is OK
typedef Aspect1<Aspect2<DerivedA> > > ClassToBeUsed; // This is not (Aspect1 specialization for DerivedA is not compiled)

一种可能性是,从 DerivedA 派生的任何类都使用专业化 Aspect1。有没有办法做到这一点(也许使用一些boost::is_base_ofboost::enable_if(?

我以为我可以在DerivedA体中使用一些typedef DerivedA AspectBase;,但我看不出如何将Aspect1模板类专用于模板类参数中的 typedef。

感谢您的建议!

你不能

,唯一可以确定的方法是是否使用Aspect1<DerivedA>类型。如果使用,则将其编译,否则不编译。