【问题标题】:Unable to deduce type in class with constructor taking std::array无法使用采用 std::array 的构造函数推断类中的类型
【发布时间】:2020-05-27 12:17:15
【问题描述】:

我正在尝试创建一个包含枚举字符串对的模板类,但无法进行类型推断。使用以下代码我有两个问题:

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"}
}}};
  1. 为什么编译器不能在构造函数中自己推导出 EnumToString 的参数?
  2. 为什么用户扣除指南没有帮助?

【问题讨论】:

    标签: c++ c++17


    【解决方案1】:

    {..} 没有类型,无法推断(std::initializer_list&lt;T&gt;T(&amp;)[N] 除外)。

    所以常规构造函数或推导指南对 CTAD 没有帮助。

    【讨论】:

      【解决方案2】:

      正如@Jarod42 所提到的,原因是在 C++ 中,大括号初始值设定项没有任何类型,并且编译器无法在模板上下文中推断出来。其原因已总结here

      要修复它,您可以使用auto 变量来推断类型,然后将其传递给您的模板方法。

      auto x = {{One, "One"}, {Two, "Two"}};
      // Now x has a type, you can pass it to a template function. 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        • 2015-10-31
        • 1970-01-01
        相关资源
        最近更新 更多