【发布时间】:2020-12-07 04:27:33
【问题描述】:
我有一个类 A 正在尝试调用非成员函数 DoTheThing。 DoTheThing 是类 A 的朋友,因此它可以调用 A 的私有成员函数 TheThing。 DoTheThing 是一个模板函数,因此它可以在多个用户定义的类中调用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