我有一个类模板,我想为其引入几个模板特化。这些模板特化与某些现有类型相同。从概念上讲,我想将它们实现为别名/typedef。
下面的示例代码应该显示我想要做什么:
template<class T> class Common {
/// general implementation
};
class TypeZ;
template<> class Common<Type1> = TypeZ; // <<< how to do this?
template<> class Common<Type2> = TypeZ;
template<> class Common<Type3> = TypeZ;
在 C++(或 C++11)中,以上内容是否可以某种方式实现?如果我不必实现 Common<...>
就好了作为继承 TypeZ
的类- 实际代码比上面显示的更复杂并且继承了TypeZ
这不是一个好主意。
最佳答案
假设只有 Common
的某些特化是 TypeZ
的别名那么你可以这样做:
template<class T> class Common {
struct type {
/// general implementation
};
};
template<> class Common<Type1> { using type = TypeZ; };
template<> class Common<Type2> { using type = TypeZ; };
template<> class Common<Type3> { using type = TypeZ; };
template<class T> using common_t = typename Common<T>::type;
然后你使用common_t<T>
而不是 Common<T>
.
娱乐一下继承思路,你试过吗?
template<> class Common<Type1> : public TypeZ { using TypeZ::TypeZ; };
template<> class Common<Type2> : public TypeZ { using TypeZ::TypeZ; };
template<> class Common<Type3> : public TypeZ { using TypeZ::TypeZ; };
那么你不需要使用嵌套类型别名。
关于c++ - 是否可以将实现模板特化定义为另一种类型的 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20419869/