c++ - 从模板中的另一个类名派生一个类名

标签 c++ templates arguments class-names

为了使用库,我需要使用具有相同基名的不同类。即

MyClass
MyClassImpl
PreMyClass

等等。为了将它们与模板一起使用,我需要传递所有这些类名。

template <typename T, typename TImpl, typename PreT>
class ClassThatUsesAllTheseObjects
{
  public:
  ClassThatUsesAllTheseObjects();
  private:
  T myClass;
  TImpl myClassImpl;
  PreT myPreClass;
};

仅将主要 MyClass 作为模板参数,在需要时构建其他名称是否可以获得相同的结果?

最佳答案

我不确定你问题中的设置,但在某些情况下,你可能想做类似 trait mechanism 的事情。 .

假设你写了一个具体的MyClass,其他人也喜欢它。对于每组具体类,您可以执行以下操作:

// This is common
template <typename T>
struct foo_traits
{

};

// This is for each set of concrete classes
template<>
struct foo_traits<MyClass>
{
   using Impl = MyClassImpl;
   using Pre = PreMyClass; 
};

...

然后像这样使用 traits 类:

template <
    typename T, 
    class Impl = typename foo_traits<T>::Impl,
    class Pre = typename foo_traits<T>::Pre>
class ClassThatUsesAllTheseObjects
{
  public:
  ClassThatUsesAllTheseObjects();
  private:
  T myClass;
  Impl myClassImpl;
  Pre myPreClass;
};

这让您可以解释您的主要具体类的“自然 friend ”是什么。

关于c++ - 从模板中的另一个类名派生一个类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30751728/

相关文章:

c++ - 'Try This' vector 使示例词典中的单词发出蜂鸣声。编程原则与实践

javascript - 如何将 Web 组件分离到单个文件并加载它们?

Android – 是否可以使用非字符串参数制作 Http-Post?

python - 将字符串作为元组作为参数传递 python

c++ - 在 C++ 中使用字符串作为参数和参数或返回类型的正确方法是什么

c++ - 关于类和对象的初学者问题

c++ - C++-17 中专门化的模式匹配中 lambda 的拆分函数签名

c++ - 将文本标记为类型、字符串对

c++ - 将 std::conditional 与不可转换类型一起使用(原始与指针)

c++ - 特化模板<typename T, template<typename> class U>