c++ - 为什么这个初始化列表不能匹配模板参数?

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

#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"}));

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

最佳答案

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

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

您只能将其用于扣除

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

关于c++ - 为什么这个初始化列表不能匹配模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53187640/

相关文章:

c++ - 处理 std::variant 中的循环依赖

c++ - 为类模板实现一个类型特征,该类型特征对于实际的类模板和继承它的类都是正确的

c++ - 使用 QGraphicsScene 平滑动画

C++:错误 LNK:无法解析的外部符号,由虚函数产生

c++ - 基于修改后的quick_sort的nth_element实现,未按预期工作

c++ - 源文件中成员函数模板的显式特化

c++ - 通用运算符 T() 的 enable_if

c++ - 使用非 const 构造 const 对象

c++ - 使用来自可变参数模板类的特定参数调用函数

c++ - for 语句中的 constexpr