是否可以将实现模板专门化定义为另一种类型的typedef? [英] Is it possible to define an implementation template specialization as typedef of another type?

查看:135
本文介绍了是否可以将实现模板专门化定义为另一种类型的typedef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类模板,我要介绍几个模板专门化。那些模板专业化与某些现有类型相同。从概念上来说,我想将它们实现为别名/ typedef。

I have a class template for which I want to introduce several template specializations. Those template specializations identical to some existing type. Conceptually I would like to implement them as aliases/typedefs.

以下示例代码应该显示我想做什么:

The following example code should show what I want to do:

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 是不是一个好主意。

Is the above possible in some way in C++ (or C++11)? It would be great if I didn't have to implement Common<...> as a class that inherits TypeZ - the actual code is more complex than shown above and inheriting TypeZ is not a good idea there.

推荐答案

假设 Common 的某些专业化是 TypeZ 的别名,

Assuming only certain specialisations of Common are aliases of TypeZ then you can do:

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>

Then you use common_t<T> rather than 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; };

然后,您不需要使用嵌套类型别名。

Then you don't need to use a nested type alias.

这篇关于是否可以将实现模板专门化定义为另一种类型的typedef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆