Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

c++ - Is it possible to infer template parameters of tuple from brace-type initialization?

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)
}

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.

(Also, although similar, this has nothing to do with initializer_list since it doesn't work at all having dissimilar elements in the braces)

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)


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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...