gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:33:46 26 4
gpt4 key购买 nike

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com