【问题标题】:Why am I getting the error operator() cannot be overloaded?为什么我得到错误 operator() 不能重载?
【发布时间】:2012-12-23 13:37:31
【问题描述】:

我有两个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);
}

这些错误仅在第一个模板参数Tvoid 时发生。我想知道我做错了什么以及为什么我不能以这种方式超载operator()

【问题讨论】:

  • 您已经定义了两个具有相同签名的名为operator() 的函数。你期待什么?
  • @n.m.当且仅当Tvoid 时,我才想使用第二个operator() 重载。这基本上就是我想要做的,但 Pubby 为我清除了它。
  • 出于同样的原因 std::tuple 有一个损坏的构造函数规范。见stackoverflow.com/questions/11386042/…
  • 语言/编译器不知道您要使用哪个定义,因此它会标记错误。没有简单的方法告诉编译器“如果有两个,我想使用这个”,所以你只需要提供一个定义。 Pubby 的建议是确保只有一个的一种方法。另一种方法是使用 SFINAE 和 std::enable_if 之类的东西。如果您的 struct A 变得太大而无法方便地进行专业化,您可能需要研究第二个选项。

标签: c++


【解决方案1】:

好吧,如果 Tvoid,那么您有两个具有完全相同原型的函数定义 - 破坏 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)) {}
};

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-04-06
  • 2021-08-23
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多