为了实现通用编程,我创建了以下代码:
#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.
据我所知,根据静态地址的信息来看,这将产生两个不同的函数,因此它似乎是一种模板缩写。我的直觉是,维护一个函数比维护多个函数更好,但除了注意非共享静态变量外,我是否错过了某些东西,使得这是一个不良的选择,而不是多个函数定义?
auto
... 对于函数,请使用模板。 - WhiZTiM