【问题标题】:"No instance of overloaded function" error with static friend template function静态友元模板函数出现“无重载函数实例”错误
【发布时间】:2020-12-07 04:27:33
【问题描述】:

我有一个类 A 正在尝试调用非成员函数 DoTheThingDoTheThing 是类 A 的朋友,因此它可以调用 A 的私有成员函数 TheThingDoTheThing 是一个模板函数,因此它可以在多个用户定义的类中调用TheThing。因为错误引用了一个重载的函数,我相信我在A 中重新定义了DoTheThing,但我不知道如何修复这个错误。

#include <iostream>
#include <vector>

template<typename Component>
    requires requires (std::vector<double>& vec, int i) {Component::TheThing(vec, i); }
    static void DoTheThing(std::vector<double>& vec, int i) {
        Component::TheThing(vec, i);
    }


class A {
    template<class Component>
    friend void DoTheThing(std::vector<double>& vec, int i);
public:
    A() {
        vec_.resize(10, 5);
        DoTheThing<A>(vec_, 7); // Error: no instance of overloaded function
    }
private:
    static void TheThing(std::vector<double>& vec, int i) {
        vec[i] = vec[i] * i;
    }


    std::vector<double> vec_;
};

我是在重新定义DoTheThing吗?如何让非会员 DoTheThing 成为 A 的朋友?如何在A的构造函数中调用DoTheThing

【问题讨论】:

  • Component::TheThing(vec, i); 无效。它是一个非静态成员函数,所以你需要一个对象来调用它。即使有一个对象,TheThing 也是私有的。另外,添加requires 子句中的错误,它很有用。
  • @cigien 是的,TheThing 应该是静态的。如果DoTheThing是A班的朋友,不应该可以访问吗?而且我从 requires 子句中也没有错误。确保您使用的是 C++20。
  • requires 子句肯定有错误。这就是调用实际失败的地方。

标签: c++ templates friend-function


【解决方案1】:

您没有使用特别的 requires 子句来限制 friend 声明,因此您实际上并没有将友谊授予您想要的同一 DoTheThing 函数。您还需要在friend 声明中复制requires 子句:

class A {
    template<class Component>
    requires requires (std::vector<double>& vec, int i) {Component::TheThing(vec, i); }
    friend void DoTheThing(std::vector<double>& vec, int i);
// ...
};

这是demo


不过,你应该给这个概念命名,使用起来会更简单:

template<typename Component>
concept CanDoThing = requires (std::vector<double>& vec, int i) { 
  Component::TheThing(vec, i); 
};

template<CanDoThing Component>
static void DoTheThing(std::vector<double>& vec, int i) {
  Component::TheThing(vec, i);
}

class A {
  template<CanDoThing Component>
  friend void DoTheThing(std::vector<double>& vec, int i);
// ...
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    相关资源
    最近更新 更多