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)
bip*_*pll 21
decltype(var_a) var_b;
Run Code Online (Sandbox Code Playgroud)
并且Lorem Ipsum每个答案达到所需的最少30个字符.
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)
为了完整起见,也许值得一提.
我不是在寻找它的信用,几乎与上面提到的答案相同,但我发现它更具可读性.
在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)
归档时间: |
|
查看次数: |
2939 次 |
最近记录: |