[英]Unable to deduce type in class with constructor taking std::array
I am trying to create a templated class containing enum-string pairs and unable to make type deduction work.我正在尝试创建一个模板化的 class 包含枚举字符串对并且无法进行类型推断。 With a following code i have two problems:
使用以下代码我有两个问题:
namespace {
template<typename T, size_t S>
using EnumStringArray = std::array<std::pair<T, const char*>, S>;
}
template<typename T, size_t S>
class EnumToString {
public:
constexpr EnumToString(const EnumStringArray<T, S>& array) :
_array(array)
{}
private:
EnumStringArray<T, S> _array;
};
template<typename T, size_t S>
EnumToString(const EnumStringArray<T, S>&) -> EnumToString<T, S>;
enum MyEnum {
One,
Two
};
constexpr EnumToString enumStrings = {{{ //<---- does not compile without explicit types
{One, "One"},
{Two, "Two"}
}}};
{..}
has not type and cannot be deduced (except as std::initializer_list<T>
or T(&)[N]
). {..}
没有类型并且不能被推断(除了std::initializer_list<T>
或T(&)[N]
)。
so regular constructor, or deduction guide doesn't help with CTAD here.所以常规的构造函数或推导指南对 CTAD 没有帮助。
The reason, as has mentioned by @Jarod42, is that in C++ brace initializers do not have any types and cannot be deduced by the compiler in the context of templates.正如@Jarod42 所提到的,原因是在 C++ 中,大括号初始值设定项没有任何类型,并且编译器无法在模板上下文中推断出。 The reason of this has been summarized here .
其原因已在此进行了总结。
To fix it, you can use an auto
variable to deduce the type and then pass it to your template method.要修复它,您可以使用
auto
变量来推断类型,然后将其传递给您的模板方法。
auto x = {{One, "One"}, {Two, "Two"}};
// Now x has a type, you can pass it to a template function.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.