定义与变量a相同类型的变量b

时间:2016-05-23 14:21:08

标签: c++ templates c++11 traits

是否可以声明与另一个变量var_b相同类型的变量var_a

例如:

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 个答案:

答案 0 :(得分:41)

当然,请使用decltype

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

您可以向decltype说明符添加cv限定符和引用,就像它是任何其他类型一样:

const decltype(var_a)* b;

答案 1 :(得分:21)

decltype(var_a) var_b;

Lorem Ipsum每个答案达到所需的最少30个字符。

答案 2 :(得分:12)

尽管@TartanLlama的答案很好,但这是另一种可以使用decltype来命名实际给定类型的方法:

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

为了完整起见,也许值得一提。

我不是在寻找学分,它与上面提到的答案几乎相同,但我觉得它更具可读性。

答案 3 :(得分:6)

在c ++ 11之前的古代,人们使用纯模板来处理它。

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

}
相关问题