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

use*_*652 24 c++ templates traits c++11

是否可以声明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) {

}
Run Code Online (Sandbox Code Playgroud)

Tar*_*ama 41

当然,使用decltype:

auto var_a = bar(t);
decltype(var_a) b;
Run Code Online (Sandbox Code Playgroud)

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

const decltype(var_a)* b;
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用[`std :: remove_reference`](http://en.cppreference.com/w/cpp/types/remove_reference)解决参考问题:`std :: remove_reference <decltype(var_a)> :: type b;` (4认同)

bip*_*pll 21

decltype(var_a) var_b;
Run Code Online (Sandbox Code Playgroud)

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

  • 如果你的答案只是代码,那么你需要为它添加废话,那么问问自己这是否是一个好的(好的!=有帮助的)答案.例如,考虑链接到[documentation](http://en.cppreference.com/w/cpp/language/decltype). (11认同)
  • Lorem Ipsum卖给我了. (9认同)
  • @Tas,"改进的余地",你的意思是在对"使用decltype"这样的解释进行解释,并假设op无法推断出我建议在代码片段中使用decltype吗?或者op无法搜索关键字以根据需要获取其他详细信息?对不起,我不是那个假设.:( (7认同)
  • 但是,如果您觉得OP需要搜索更多细节,那么您的答案是否只能提供详细信息或指向所述详细信息的链接,而不是直接写废话的线索?我不是说写一篇关于`decltype`的文章,但如果你不得不写废话,_I_觉得提供一个链接会更有建设性.无论如何,你的答案是有帮助的(给OP提供必要的信息等),我觉得你需要写的额外字符可能会更好用. (2认同)

sky*_*ack 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(); }
Run Code Online (Sandbox Code Playgroud)

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

我不是在寻找它的信用,几乎与上面提到的答案相同,但我发现它更具可读性.


W.F*_*.F. 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) {

}
Run Code Online (Sandbox Code Playgroud)