c++ - 为什么我收到错误 operator() cannot be overloaded?

标签 c++

我有两个重载 operator() ,一个接受函数引用的函数引用,该函数引用将任何类型作为其参数并返回任何类型。另一个采用函数引用,该函数引用采用任何类型作为其参数但返回 void .在实例化我的类时,出现以下错误:

In instantiation of 'A<void, int>':
error: 'void A<T, F>::operator()(void (&)(F)) [with T = void, F = int]' cannot be overloaded
error: with 'void A<T, F>::operator()(T (&)(F)) [with T = void, F = int]'

template <typename T, typename F> struct A {
    void operator()(T (&)(F)) {}
    void operator()(void (&)(F)) {}
};

void f(int) {}

int main() {

    A<void, int> a;
    a(f);
}

这些错误仅在第一个模板参数 T 时发生是void .我想知道我做错了什么以及为什么我不能重载 operator()这条路?

最佳答案

好吧,如果 Tvoid 那么你有两个具有完全相同原型(prototype)的函数定义 - 打破了 ODR。

尝试专门化你的结构来防止这种情况:

template <typename T, typename F> struct A {
    void operator()(T (&)(F)) {}
    void operator()(void (&)(F)) {}
};

template <typename F> struct A<void, F> {
    void operator()(void (&)(F)) {}
};

关于c++ - 为什么我收到错误 operator() cannot be overloaded?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14011399/

相关文章:

c++ - 自己的lib,另一台电脑: cannot open shared object file: No such file or directory

C++动态绑定(bind)问题

c++ - 如果标准指定它有一个析构函数,类应该不是可简单破坏的吗?

c++ - 在多线程库中转换 future

c++ - std::string 与模板一起使用,检查是否为空

c++ - 在 Windows 和 Qt5 上使用 SendMessage 进行进程间通信

c++ - 提升在多个线程上运行的 asio strand 和 io_service

c++ - 两步到一步初始化和错误处理

c++ - 为什么带有自定义删除器的 unique_ptr 不适用于 nullptr,而 shared_ptr 可以?

c++ - 为什么 unsigned int 0xFFFFFFFF 等于 int -1?