混合使用别名和模板专业化

时间:2019-05-03 11:52:58

标签: c++ c++11 templates template-meta-programming template-deduction

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

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

我的解决方法是:

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中指定code参数,我想避免这种情况。

例如:

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

有没有办法实现我想要的?可以同时更改doSomething或A实现。

1 个答案:

答案 0 :(得分:2)

如果您试图基于调用类型来定制[build] |-- blocks.editor.build.css |-- index.js |-- blocks.style.build.css |-- style.js (ignore) |-- editor.js (ignore) |-- css.js (ignore) `-- (...and indentical map files) 的行为,则编译器将无法从doSomething推论出东西(以前是answered)。但是您可以通过提供traits形式的自定义点来告诉它需要知道什么。例如:

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; }; ,并且只要他们尊重您使用特质制定的合同,您的代码就可以为他们工作。