在这个例子中,是否可以允许推导元组
的模板参数类型?
#include<tuple>
#include<string>
template<class T1, class T2>
void fun(std::tuple<T1, T2> t, std::string other){}
int main(){
fun(std::tuple<double, int>(2.,3), std::string("other")); // ok
fun(std::make_tuple(2.,3), std::string("other")); // ok, but trying to avoid `make_tuple`
fun({2.,3},std::string("other")); // desired syntax but
// giving compilation error: candidate template ignored: couldn't infer template argument 'T1' void fun(std::tuple<T1, T2> t)
}
我添加了第二个参数 other
以避免在函数 fun
级别涉及可变参数的解决方案。此外,我试图避免使用 make_tuple
,至少在用户代码中(即在 main()
中)。事实上,它不需要是 tuple
类型,只要允许“所需的语法”,并且可以在后期以某种方式推断出它的元素类型。
(另外,虽然相似,但这与 initializer_list
无关,因为它在大括号中有不同的元素根本不起作用)
它至少在 clang 3.2
和 gcc 4.7.2
中失败。它是否有希望适用于当前或近期的标准? (例如, future (?)initializer_tuple
。)
(这对于通过聚合子元素来增加函数调用的表现力非常有用,但可以争论)
注意:对于示例代码,std::forward_as_tuple
似乎比 std::make_tuple
更合适,因此不一定要复制参数:http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple .仍然不如异构初始化列表的内置语言功能好。
最佳答案
不行,绝对没有办法。如果元素类型不是同一类型,则推导失败。如果参数不是 std::initializer_list<T>
,则根本不会进行任何扣除。无论如何(你是对的,initializer_list
与你给出的大括号没有任何关系,但这是演绎工作的简单规则)。
模板参数值必须由涉及它们的其他函数参数位置推导或必须明确指定。
关于c++ - 是否可以从大括号类型的初始化中推断出元组的模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16703838/