【发布时间】:2015-07-18 16:09:51
【问题描述】:
我有一个关于模板函数与函数的自动类型推导的一般性问题。
多年来,我们已经能够编写模板函数:
template <class T> T add(T a,T b){
return a+b;
}
函数的参数推导有一个使用auto的TS
auto add(auto a,auto b){
return a+b;
}
我虽然使用自动,但无法获取实际类型,例如使用静态成员,但这很好用:
#include <iostream>
struct foo
{
static void bar(){std::cout<<"bar"<<std::endl;}
static int i ;
};
int foo::i{0};
void t(auto f){
decltype(f)::bar();
std::cout<< decltype(f)::i<<std::endl;
}
int main(int argc, char *argv[])
{
t(foo());
return 0;
}
那么有什么理由选择一个而不是另一个?
【问题讨论】:
-
C++14 不允许对函数参数类型使用
auto,只能推断返回类型。您所使用的(作为编译器提供的扩展)是最终会在 Concepts Lite 标准化时进入标准的语法。 -
auto无论如何都对类型使用模板类型推导。 -
@FoggyDay:主要有两个原因。首先是避免冗长。二是避免因同类型的冗余规范而降低可维护性。
-
请注意,您可以只写
f.bar()和f.i来访问静态成员。 -
@T.C.
using T = decltype(f);;)
标签: c++ templates auto c++14 c++17