在泛型编程的精神,我创建了下面的代码:是否存在使用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.
从我可以通过静态地址告诉,这将产生两个不同的功能,所以在我看来就像一个模板速记,一种。我的直觉是,要维护的一个功能比多个功能要好,但是,除了要注意非共享静态变量,我是否错过了一些可能使其成为糟糕选择的东西,而不是多个函数定义?
只能在通用lambdas中使用'auto' ...对于函数,使用模板 – WhiZTiM
这是一个非标准的扩展,模板的简写,显然[可能会添加到C++ 17标准]( http://stackoverflow.com/questions/25879705/is-auto-as-a-parameter-in-a-regular-function-a-gcc-4-9-extension)。不是C++的一部分14。 – HostileFork
@HostileFork不会在C++中17。 – Barry