类模板中使用constexpr遇编译错误的原因及解决咨询
问题原因与解决办法
错误原因
constexpr是用来修饰常量表达式变量、函数或模板的关键字,不能直接用在using定义类型别名的语法里。using的作用是给现有类型起别名,它本身是类型声明,不是可被constexpr修饰的实体,编译器自然会报错说“在constexpr之前缺少类型说明符”——因为它根本不认识放在这里的constexpr。
解决办法
要让你的refaofAints成为常量表达式,应该把constexpr放在变量声明上,而不是类型别名arrayofAs的定义里。举个具体的代码例子:
首先是正确的unref模板实现:
template<typename T> struct unref { using type = T; }; template<typename T> struct unref<T&> { using type = T; }; template<typename T> struct unref<T&&> { using type = T; }; // 辅助别名模板,简化使用 template<typename T> using unref_t = typename unref<T>::type;
然后定义类型别名和常量表达式变量:
// 假设A是某个自定义类型 struct A {}; // 正确:using只定义类型别名,不加constexpr using arrayofAs = std::array<unref_t<A&>, 5>; // 把constexpr放在变量声明上,让变量成为常量表达式 constexpr arrayofAs refaofAints{};
这样就能解决最初的“非constexpr”问题,同时避免编译错误——因为我们把constexpr用在了正确的位置:修饰变量,而不是类型别名。
内容的提问来源于stack exchange,提问作者Vinod
相关产品推荐
相关产品推荐

