C++20中枚举类成员作为模板特化参数报错问题咨询
问题原因及解决办法
你的编译错误核心原因很直接:
- 你定义的模板
template <typename T> struct S是类型模板参数,要求传入的必须是一个类型(比如int、std::string、自定义类等)。 - 但
EClass::A是枚举类EClass的一个枚举值(常量),它是一个值而非类型,不符合模板参数的要求,因此编译器报错。
两种解决思路
思路1:改用非类型模板参数
如果你的需求是基于枚举值做模板特化,把模板改成接受EClass类型的非类型参数即可:
enum class EClass { A, B, C, D, E }; // 模板参数改为EClass类型的非类型参数,接受枚举值 template <EClass Val> struct S; template <> struct S<EClass::A> { static constexpr std::string_view name = "A"; };
思路2:将枚举值包装为类型
如果坚持要用类型模板参数,可以用std::integral_constant把枚举值包装成一个类型,再传给模板:
#include <type_traits> enum class EClass { A, B, C, D, E }; template <typename T> struct S; // 用std::integral_constant把EClass::A包装成类型 template <> struct S<std::integral_constant<EClass, EClass::A>> { static constexpr std::string_view name = "A"; };
额外说明:C++中枚举类的成员本质是编译期常量,和类的嵌套类型、typedef这类类型成员完全是两回事,不能混为一谈。
内容的提问来源于stack exchange,提问作者yonutix
相关产品推荐
相关产品推荐

