学习信号槽、模板、函数指针时想到了如下代码。
基本上我正在尝试制作 2 个类,基类将采用普通函数指针,而派生类将采用成员函数并用普通函数将其包装起来,然后将其传递给基类进行调用。
代码如下:
#include<iostream>
struct foo {
void onNotify(int a, int b) {
std::cout << "member function: this=" << this << " a=" << a << " b=" << b << "\n";
}
};
void onNotify(void*, int a, int b) {
std::cout << "normal function: no context needed! a=" << a << " b=" << b << "\n";
}
// invoker that will takes normal functions.
template <typename...>
class invoker{
public:
invoker(void (*fptr)(void*, int, int), void* context){
fptr(context, 1, 2);
}
private:
invoker(){}
};
// invoker that will takes member functions.
template<class T>
class invoker<T> : public invoker<>{
public:
invoker<T>(T* context) : invoker<>(&forwarder, context){}
private:
invoker<T>(){}
static void forwarder(void* context, int i0, int i1) {
static_cast<T*>(context)->onNotify(i0, i1);
}
};
int main()
{
invoker<>(&onNotify, 0); // OK.
invoker<foo>(new foo); // OK.
invoker<foo>(0); // OK.
foo foo_;
auto f = invoker<foo>(&foo_); // OK.
// Errors:
// C2373 : 'foo_' : redefinition; different type modifiers.
// C2530 : 'foo_' : reference must be initialized.
invoker<foo>(&foo_); // ERROR!
return 0;
}
我的问题是:
1) 什么导致编译错误?
2) 为什么 invoker<foo>(0);
真的会无误地运行吗?
提前致谢!
最佳答案
1)问题在于
invoker<foo>(&foo_);
被解析为变量 foo_
的定义类型为 invoker<foo>&
而不是调用 invoker<foo>
的 ctor .有很多方法可以解决这个问题,例如,使用额外的括号:
(invoker<foo>)(&foo_);
2)代码
invoker<foo>(0);
编译没有错误,因为它是明确的(它不能被解释为声明)。
关于c++ - 奇怪的模板和成员函数指针错误(C2373、C2530),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404503/