c++ - 奇怪的模板和成员函数指针错误(C2373、C2530)

标签 c++ pointers

学习信号槽、模板、函数指针时想到了如下代码。

基本上我正在尝试制作 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/

相关文章:

c++ - 将负数存储在无符号整数中

c++ - 如何从点源模拟二维球面波?

使用指针将 C 语言转换为 MIPS 程序集

c++循环在每次迭代时变慢

c++ - 寻找调试棘手的 Windows 服务启动 gremlin 的想法

c++ - tbb 中 parallel_reduce 的 Reduce 是什么?

pointers - 将指针字段分配给强制转换的值

c++ - 使用函数指针将 C 转换为 CPP

c++ - 如何在函数中分配指向新对象的指针,而该对象在编辑后不会消失

C++ string() 与 c 字符串的比较。为什么这行得通?