【发布时间】:2016-04-15 15:47:10
【问题描述】:
本着泛型编程的精神,我创建了以下代码:
#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.
从静态地址可以看出,这会产生两个不同的函数,所以在我看来,它就像是模板的简写形式。我的直觉是维护一个函数比维护多个函数要好,但是,除了注意非共享静态变量之外,我是否遗漏了一些可能使其成为糟糕选择的东西,而不是多个函数定义?
【问题讨论】:
-
你只能在泛型 lambda 中使用
auto... 对于函数,使用模板 -
它是一个非标准扩展,是模板的简写,显然是likely to be added to the C++17 standard。不是 c++14 的一部分。
-
@HostileFork 不会出现在 C++17 中。
-
@Barry 可能是最好的......但也许你可以告诉那里的答案作者,在适当的参考下从“可能”更新为“不会发生”。
-
@HostileFork 也对该答案发表了评论。