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) {
}
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;
decltype(var_a) var_b;
And a Lorem Ipsum to reach the required minimum of 30 characters per answer.
Despite the nice answer of @TartanLlama, this is another way one can use decltype
to name actually the given type:
int f() { return 42; }
void g() {
// Give the type a name...
using my_type = decltype(f());
// ... then use it as already showed up
my_type var_a = f();
my_type var_b = var_a;
const my_type &var_c = var_b;
}
int main() { g(); }
Maybe it's worth to mention it for the sake of completeness.
I'm not looking for credits for it's almost the same of the above mentioned answer, but I find it more readable.
In ancient times before c++11 arrived people dealt with it using pure templates.
template <class Bar>
void foo_impl(Bar var_a) {
Bar var_b; //var_b is of the same type as var_a
}
template <class T>
void foo(T t) {
foo_impl(bar(t));
}
F_1 bar(T_1 t) {
}
F_2 bar(T_2 t) {
}