混合别名和模板专业

Mixing aliases and template specializations

本文关键字:别名 混合      更新时间:2023-10-16

我正在尝试找到一种可以使用专业化或"链接"到另一种类型的"对象"的最佳方法。

例如,您不能专业化类使其成为一个简单的INT,并且您不能使用关键字来专门化类。

我的解决方案是:

template<class Category, Category code>
struct AImpl
  {};
template<class Category, Category code>
struct AHelper
  {
  using type = AImpl<Category, code>;
  };
template<class Category, Category code>
using A = typename AHelper<Category, code>::type;
template<int code>
void doSomething(A<int, code> object)
  {
  }
template<>
struct AImpl<int, 5>
  { 
  double a; 
  };
template<>
struct AImpl<int, 6>
  { 
  int b; 
  double c;
  };
template<>
struct AHelper<int, 7>
  {
  using type = int;
  };
template<class Category, Category code>
struct Alternative {};
template<int code>
void doSomethingAlternative(Alternative<int, code> object)
  {
  }

这有效,但您需要在Dosomething中指定代码参数,我想避免。

例如:

A<int,7> a7; // This is equivalent to int
a7 = 4;
A<int, 5> a5; // This is equivalent to AImpl<int,5>
a5.a = 33.22;
doSomething(a5); // This does not compile
doSomething<5>(a5); // This compiles but is bulky
Alternative<int,0> alt0;
doSomethingAlternative(alt0); // This compiles and is not bulky
                              // but you're forced to use class
                              // specializations only

有没有办法实现我想要的东西?可以更改滴定或A实现。

如果您试图根据所调用的类型自定义doSomething的行为,则不能使编译器从AHelpr::type中推论(如前所述(。但是,您可以通过以特征的形式提供自定义点来告诉它。例如:

template<typename T>
void doSomething(T& object)
{
    auto code = SmthTriats<T>::code;
}

考虑到SmthTriats的能力,这是高度扩展的:

template<typename> struct SmthTriats;
template<typename Category, Category code_>
struct SmthTriats<AImpl<Category, code_>> {
    static constexpr auto code = code_;
};
template<>
struct SmthTriats<int> {
    static constexpr auto code = 7;
};

特征类也允许在模块之外自定义。客户端代码只需要使用自己类型的SmthTriats专业,只要尊重您与您的特征达成的合同,您的代码将适用于他们。