本着通用编程的精神,我创建了以下代码:
#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 )
是符合标准的编译器上的编译错误。