是否可以从大括号类型初始化推断元组的模板参数?

alf*_*lfC 6 c++ tuples explicit copy-initialization c++11

在这个例子中,是否可以允许推导 的模板参数类型tuple

#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)
}
Run Code Online (Sandbox Code Playgroud)

我添加了第二个参数,other以避免涉及函数级别的可变参数的解决方案fun。另外,我试图避免使用make_tuple,至少在用户代码中(即在main())。事实上,它不需要是tuple所涉及的类型,只要允许“所需的语法”,并且可以在稍后阶段以某种方式推断出其元素类型。

(另外,虽然相似,但这无关,initializer_list因为它在大括号中具有不同的元素根本不起作用)

它至少在clang 3.2和时失败gcc 4.7.2。它是否有希望与当前或不久的将来的标准兼容?(例如未来(?)initializer_tuple。)

(这对于通过聚合子元素来增加函数调用的表现力非常有用,但这可以争论)


注意:对于示例代码,似乎std::forward_as_tuple更合适,std::make_tuple因此参数不一定被复制:http ://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple 。仍然不如异构初始值设定项列表的内置语言功能那么好。

Joh*_*itb 4

不,绝对没有办法。如果元素类型不同,则推导失败。如果参数不是 a ,则根本不会进行任何推导std::initializer_list<T>(你是对的,initializer_list与你给出的大括号没有任何关系,但这是推导工作的简单规则)。

模板参数值必须由涉及它们的其他函数参数位置推导或者必须显式指定。