标识功能:模板和自动之间的区别



我正在为我的一些类编写一个标识函数,该函数会记录调用次数(长话短说:metrics(。

目前,我正在尝试计算使用模板与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; };

在运行时,哪一个更快?它们有编译时间差吗?

由于这个函数经常被称为,我对运行时性能更感兴趣,但也可能有大量类型需要为其生成函数,所以我也对编译时哪种类型更快感兴趣。

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)

是否意味着

// not this
template <class T>
T foo(T a)

返回类型将从foo定义中的返回表达式推导出来,就像任何auto返回类型一样。恰好在函数中,返回类型被推断为与参数类型相同。

多个auto参数

void foo(auto a, auto b)

是否等同于

// not this
template <class T>
void foo(T a, T b)

但使用

template <class T, class U>
void foo(T a, U b)

最新更新