加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用auto作为参数是否有负面影响?

发布时间:2020-12-16 10:02:20 所属栏目:百科 来源:网络整理
导读:本着通用编程的精神,我创建了以下代码: #include iostream#include functionalclass Functor{public: void operator()() { std::cout "Functor operator called." std::endl; }};void Function(){ std::cout "Function called." std::endl;}void Call( auto
本着通用编程的精神,我创建了以下代码:

#include <iostream>
#include <functional>

class Functor
{
public:
    void operator()()
    {
        std::cout << "Functor operator called." << std::endl;
    }
};

void Function()
{
    std::cout << "Function called." << std::endl;
}

void Call( auto & fp )
{
    static int i;
    std::cout << "Unified calling..." << &i << std::endl;
    fp();
}

int main( int argc,char ** argv )
{
    Functor functor;
    std::function< void() > function = Function;

    std::cout << "Begin testing..." << std::endl;
    Call( functor );
    Call( function );
    std::cout << "End testing." << std::endl;

    return 0;
}


Compiled with: g++ main.cpp -std=c++14
output:
Begin testing...
Unified calling...0x100402080
Functor operator called.
Unified calling...0x100402090
Function called.
End testing.

从静态地址我可以看出,这产生了两个不同的功能,所以在我看来,它就像一个模板简写,一种类型.我的直觉是,要维护的一个函数优于多个函数,但是,除了注意非共享的静态变量之外,我是否遗漏了一些可能使这个选项变得糟糕而不是多个函数定义的东西?

解决方法

是的,有.目前的C标准禁止使用它们.

void Call( auto & fp )

是符合标准的编译器的编译错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读