是否可以从大括号类型初始化中推断元组的模板参数?
在这个例子中,是否可以允许对tuple
的模板参数类型进行推导?
In this example, is it possible to allow the deduction of the template parameters type of the 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)
}
我添加了第二个参数 other
以避免在函数 fun
级别涉及可变参数的解决方案.另外,我试图避免使用 make_tuple
,至少来自用户代码(即在 main()
中).事实上,只要允许所需的语法"并且可以在稍后阶段以某种方式推断出它的元素类型,它就不需要是 tuple
类型.
I added the second argument other
to avoid solutions involving variadic arguments at the level of the function fun
. Also, I am trying to avoid the use of make_tuple
, at least from the user code (i.e. in main()
). In fact it doesn't need to be the tuple
type the one involved as long as the "desired syntax" is allowed and somehow its element types can be deduced at later stage.
(另外,虽然类似,但这与 initializer_list
无关,因为在大括号中包含不同的元素根本不起作用)
(Also, although similar, this has nothing to do with initializer_list
since it doesn't work at all having dissimilar elements in the braces)
至少在 clang 3.2
和 gcc 4.7.2
上会失败.有没有希望它适用于当前或近期的标准?(例如,未来(?)initializer_tuple
.)
It fails at least with clang 3.2
and gcc 4.7.2
. Is there any hope that it would work with the current or a near-future standard? (e.g. a future(?) initializer_tuple
.)
(这对于通过聚合子元素来增加函数调用的表现力非常有用,但这可以争论)
(This can be very useful to add expressiveness to function calls, by aggregating subelements, but that can be argued about)
注意:对于示例代码,似乎 std::forward_as_tuple
比 std::make_tuple
更合适,因此不必复制参数:http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple.仍然不如异构初始化列表的内置语言功能那么好.
Note: For the example code it seems that std::forward_as_tuple
is more appropriate than std::make_tuple
so the arguments are not necessarily copied: http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple . Still not as nice as if there were a build-in language feature for heterogeneous initializer lists.
推荐答案
不,绝对没有办法.如果元素类型不是同一类型,则扣除失败.如果参数不是 std::initializer_list<T>
则根本不会进行任何推断(您是对的, initializer_list
与你给的括号,但这是扣除工作的简单规则).
No, there is absolutely no way. Deduction fails if the element types are not of the same type. And no deduction is done at all if the parameter is not a std::initializer_list<T>
anyway (you are right that initializer_list
doesn't have anything to do with the braces you give, but this is the simple rule for deduction to work).
模板参数值必须由涉及它们的其他函数参数位置推导出或必须明确指定.
The template parameter values must be deduced by other function parameter positions involving them or must be explicitly specified.
相关文章