身份功能:模板和自动之间的区别

时间:2021-07-12 16:31:55

标签: c++ templates auto

我正在为我的一些类编写一个标识函数,以保持其调用的计数(长话 -> 简而言之:指标)。

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

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

因为这个函数被调用很多,我对运行时性能更感兴趣,但也可能有大量的类型来生成函数,所以我我还想知道哪一个在编译时会更快。

1 个答案:

答案 0 :(得分:4)

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)
相关问题