【问题标题】:Why can't this initializer-list match to a template argument?为什么这个初始化列表不能匹配模板参数?
【发布时间】:2018-11-07 10:29:32
【问题描述】:
#include <iostream>

class Foo
{
public:

    template <typename Container>
    Foo (const Container & args)
    {
        for (auto arg : args)
            std::cout << "ARG(" << arg << ")\n";
    }
};

int main ()
{
    Foo foo ({"foo", "bar", "baz"});
}

错误(使用g++ -std=c++17)是

error: no matching function for call to ‘Foo::Foo(<brace-enclosed initializer list>)’

这行得通

Foo foo (std::vector<const char*> ({"foo", "bar", "baz"}));

为什么初始化列表不能匹配模板构造函数?

【问题讨论】:

    标签: c++ templates c++17 initializer-list template-argument-deduction


    【解决方案1】:

    {"foo", "bar", "baz"}没有类型,所以不能推导出来

    template <typename Container>
    Foo (const Container&);
    

    你只能用来抵扣

    template <typename T>
    Foo (const std::initializer_list<T>&);
    

    【讨论】:

      【解决方案2】:

      正如 Jarod42 所解释的,{"foo", "bar", "baz"} 没有类型,因此不能推导出为 template &lt;typename Container&gt; Foo (const Container&amp;)

      另一种可能的解决方案是

      template <typename T, std::size_t N>
      Foo (T const (& arr)[N])
      {
          for (auto arg : arr)
              std::cout << "ARG(" << arg << ")\n";
      }
      

      所以{"foo", "bar", "baz"} 被推断为具有正确大小 (3) 的 C 样式数组的初始化列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-13
        • 2017-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多