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

Are there negative ramifications of using auto as a parameter?

本着泛型编程的精神,我创建了以下代码:

#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.

据我从静态地址可以看出,这产生了两个不同的函数,所以在我看来它有点像模板 shorthand。我的直觉是维护一个函数比维护多个函数要好,但是,除了注意非共享静态变量之外,我是否遗漏了一些可能使它成为糟糕选择的东西,而不是多个函数定义?

是的,有。当前的 C++ 标准禁止使用它们。

void Call( auto & fp )

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

这是不可能的,这是主要缺陷。

auto 仅表示初始化时的类型推导。它不是 "any" 类型。因此,以这种方式使用 auto 意味着您的函数必须是模板。在 C++17 中,这将是可能的,而且 auto 参数确实会自动使函数成为模板(我个人觉得这非常令人困惑,但哦好吧)。但是现在,没有。