我正在为我的一些类编写一个身份函数,用于记录其调用的计数(长话短说:指标)。
目前,我正在尝试计算使用模板与使用模板的性能差异/优点auto
.
这是从我正在做的代码中摘取的一个简短示例:
namespace Metrics {
unsigned long identifications = 0;
//auto version
auto identity(auto i) {
//... other stuffs
identifications++;
return i;
};
//template version
template<class I> I identity(I i) {
//... other stuffs
identifications++;
return i;
};
};
还有更多事情要做,但这是基础知识。我知道编译器只会为每个函数创建一个函数,即
identity(5);
identity("5");
//generates the functions
int identity(int i) { ... return i; };
const char* identity(const char* i) { ... return i; };
在运行时,哪个更快?
他们有编译时间差异吗?
因为这个函数应该被调用a lot,我对运行时性能更感兴趣,但也可能有大量类型可以为其生成函数,因此我也对哪种类型在编译时更快感兴趣。
auto identity(auto i)
{
//...
return i;
}
是一个简写
template <class T>
auto identity(T i)
{
// ...
return i;
}
这又是一个简写
template <class T>
T identity(T i)
{
// ...
return i;
}
所以没有任何区别。
不适用于您的示例,但如果您要使用auto
您需要注意一些参数:
auto
作为返回类型
auto foo(auto a)
Does not mean
// not this
template <class T>
T foo(T a)
返回类型将从中的返回表达式推导出来foo
定义,就像任何auto
返回类型。碰巧在您的函数中,返回类型被推导为与参数类型相同。
多种的auto
参数
void foo(auto a, auto b)
Is not相当于
// not this
template <class T>
void foo(T a, T b)
but with
template <class T, class U>
void foo(T a, U b)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)