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

Define variable b of the same type as variable a

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

例如:

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

}
decltype(var_a) var_b;

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

当然,使用 decltype:

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

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

const decltype(var_a)* b;

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

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

我不是在寻找学分,因为它与上述答案几乎相同,但我发现它更具可读性。

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

}