gpt4 book ai didi

c++ - 可变参数模板不适用于初始值设定项列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:34:39 25 4
gpt4 key购买 nike

我创建了一个工厂函数模板:

template <typename M, typename... Args>
std::shared_ptr<M> create(Args... args)
{
return std::make_shared<M>(args...);
}

还有一个简单的容器:

struct Group {
std::vector<int> vec;
Group(std::initializer_list<int> il) : vec(il) {}
};

然后我尝试创建一个组

int main()
{
auto gr = create<Group>({1, 2, 3});
return 0;
}

这不编译,

error: no matching function for call to 'create'
auto gr = create<Group>({1, 2, 3});
candidate function not viable: requires 0 arguments, but 1 was provided
std::shared_ptr<M> create(Args... args)
^

但是如果我使用临时变量:

int main(int argc, char *argv[])
{
std::initializer_list<int> il = {1, 2, 3};
auto gr = create<Group>(il);
return 0;
}

确实如此。为什么?

对于这种情况,推荐的解决方案是什么?

最佳答案

模板参数不能从初始化列表中推导出来(它是一个非推导上下文),但可以从 std::initializer_list<something> 类型的表达式中推导出来。 .两者不一样。

[temp.deduct.call]/1 Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below. If removing references and cv-qualifiers from P gives std::initializer_list<P'> for some P' and the argument is an initializer list (8.5.4), then deduction is performed instead for each element of the initializer list, taking P' as a function template parameter type and the initializer element as its argument. Otherwise, an initializer list argument causes the parameter to be considered a non-deduced context (14.8.2.5). [ Example:

template<class T> void f(std::initializer_list<T>);
f({1,2,3}); // T deduced to int
f({1,"asdf"}); // error: T deduced to both int and const char*

template<class T> void g(T);
g({1,2,3}); // error: no argument deduced for T

—end example ]

关于c++ - 可变参数模板不适用于初始值设定项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41401092/

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