Search code examples
c++templatesc++11traits

Define variable b of the same type as variable a


Is it possible to declare a variable var_b of the same type as another variable, var_a?

For example:

template <class T>
void foo(T t) {

   auto var_a = bar(t);
   //make var_b of the same type as var_a

}


F_1 bar(T_1 t) {

}

F_2 bar(T_2 t) {

}

Solution

  • Sure, use decltype:

    auto var_a = bar(t);
    decltype(var_a) b;
    

    You can add cv-qualifiers and references to decltype specifiers as if it were any other type:

    const decltype(var_a)* b;