简体   繁体   中英

Is there a way to pass variables to std::make_tuple<double, char, std::string>(var1, var2)?

I want to pass variable names to std::make_tuple(), but it wouldn't let me. I'm using C++14, is there a way to achieve what I want?

std::tuple<int> get_student(int id)
{
    int gpa = 3;
    return std::make_tuple<int>(gpa);
}

This throws an error saying "cannot bind rvalue reference of type 'int&&' to lvalue of type 'int'"

I want to pass variable names to std::make_tuple()

I suppose what you really want is to return a std::tuple<int> . No make_tuple is needed for that:

std::tuple<int> get_student(int id)
{
    int gpa = 3;
    return gpa;
}

make_tuple is for deducing the type of the tuple from arguments passed to its constructor, as for example in

auto get_student(int id)
{
    int gpa = 3;
    return std::make_tuple(gpa);
}

When you deduce the tuples type from some variables, then you don't specify the template arguments.

If you do want to specify the arguments (as opposed to let them be deduced) you also do not need std::make_tuple :

auto get_student(int id)
{
    int gpa = 3;
    return std::tuple<int>(gpa);
}

Actually the whole familiy of make_ functions has the purpose to deduce some type from their arguments. There are cases where one wants to specify the argument for make_tuple , but they are not common.

Moreoever, since C++17 there is CTAD (class tempalte argument deduction), which makes many uses of make_... obsolete. Most uses I see in code here are actually just unnecessary .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM