简体   繁体   English

static 朋友模板 function 出现“没有重载函数实例”错误

[英]“No instance of overloaded function” error with static friend template function

I have a class A that is trying to call a nonmember function DoTheThing .我有一个 class A试图调用非成员 function DoTheThing DoTheThing is a friend of class A so that it can call a private member function TheThing of A . DoTheThing是 class A的朋友,因此它可以调用A的私人成员 function TheThing DoTheThing is a template function so that it can call TheThing in multiple user-defined classes. DoTheThing是一个模板 function 以便它可以在多个用户定义的类中调用TheThing Because the error references an overloaded function, I believe that I am redefining DoTheThing within A , but I cannot figure out how to fix this error.因为该错误引用了重载的 function,所以我相信我在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_;
};

Am I redefining DoTheThing ?我在重新定义DoTheThing吗? How do I make the non-member DoTheThing a friend of A ?如何让非会员DoTheThing成为A的朋友? How do I call DoTheThing in the constructor of A ?如何在A的构造函数中调用DoTheThing

You are not constraining the friend declaration with an ad-hoc requires clause, so you are actually not granting friendship to the same DoTheThing function you want.您没有使用特别的 requires 子句来限制friend声明,因此您实际上没有将友谊授予您想要的同一个DoTheThing function。 You need to replicate the requires clause in the friend declaration as well:您还需要在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);
// ...
};

Here's a demo .这是一个演示


However, you should name this concept, and the usage will be simpler:但是,你应该命名这个概念,使用会更简单:

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);
// ...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM