c++ - 是否可以将实现模板特化定义为另一种类型的 typedef?

标签 c++ templates c++11 typedef

我有一个类模板,我想为其引入几个模板特化。这些模板特化与某些现有类型相同。从概念上讲,我想将它们实现为别名/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/

相关文章:

c++ - MSVC10 中的奇怪编译器错误

c++ - 使用不同的 enable_if 条件选择成员函数

c++ - 支持 REST 和 JSON 的轻量级 NoSQL DB

c++ - 从 Qt C++ 中的另一个应用程序获取文本字段的值

Cin 之后的 C++ Getline

c++ - 对带有可变参数模板的 std::ref() 和 std::bind() 有点模糊

c++ - 模板类内部类的映射迭代器的正确语法?

.net - ISO C++ 代码是否可以在 C++/CLI 中直接编译?

c++ - C++模板中的多步推理器

c++ - 排序 vector 以将偶数和奇数 fork