Define variable b of the same type as variable a

2019-01-25 02:59发布

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

}

4条回答
一夜七次
2楼-- · 2019-01-25 03:21

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-25 03:26

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;
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-25 03:29

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

}
查看更多
女痞
5楼-- · 2019-01-25 03:37
decltype(var_a) var_b;

And a Lorem Ipsum to reach the required minimum of 30 characters per answer.

查看更多
登录 后发表回答