【问题标题】:Identity Function: Difference between templates and auto身份功能:模板和自动之间的区别
【发布时间】:2021-07-12 16:31:55
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c++ templates auto


    【解决方案1】:
    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)
    

    【讨论】:

    • 非常感谢!所以要明确一点,两者之间没有运行时或编译时差异?
    • @Werlious 什么都没有
    • @Werlious 也可以查看汇编代码或者更简单,看cppinsights
    • 明白了,感谢您的信息,我会在 10 分钟冷却后接受您的回答
    • @TedLyngmo 谢谢!我完全忘记了 cppinsights!
    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2013-06-23
    • 1970-01-01
    相关资源
    最近更新 更多