以下模板定义如何在泛型代码中包装函数指针和函数对象?
template <typename Func, typename ReturnType, typename... Arguments>
class Command
{
public:
Command(Func f) : m_func(f) { }
ReturnType operator()(Arguments... funcArgs) { return m_func(funcArgs...); }
private:
Func m_func;
};
给出一个错误信息的gcc 4.7.3(错误:字段“命令:: m_func”无效地被声明功能型)时用下面的测试代码实例化:
void testFunction(int i, double d)
{
std::cout << "TestFunctor::operator()(" << i << ", " << d << ") called." << std::endl;
}
int main()
{
void (&fRef)(int, double) = TestFunction;
Command<void(int, double), void, int, double> testCommand(fRef);
}
如果我将TestFunction没有address-of运算符传递到testCommand构造函数中,也会发生此错误消息,但如果传递了明确命名的函数指针或使用address-of运算符传递参数,则会消失。我的印象是这个代码应该在现代C++设计的第5章中有效。
背后的原因是不能存储对函数的引用,但函数指针工作正常吗?是否有任何解决方法可以在不失去支持将函子作为参数传递给Command构造函数的情况下进行编译?