"No instance of overloaded function" 静态好友模板函数错误

"No instance of overloaded function" error with static friend template function

我有一个 class A 试图调用非成员函数 DoTheThingDoTheThing 是 class A 的友元,因此它可以调用 A 的私有成员函数 TheThingDoTheThing 是一个模板函数,因此它可以在多个用户定义的 class 中调用 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

您没有使用 ad-hoc 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);
// ...
};