如何通过friend关键字声明在类中声明的非成员函数的友元函数

时间:2016-02-05 21:52:03

标签: c++ friend

我在以下代码中有两个关于朋友声明的问题。 (1)我宣布了一个朋友的功能。该程序看起来很有效,但我收到了编译器的警告。原始函数是由person声明的类中定义的非成员函数。我需要照顾它吗?或者我有问题吗? (2)如果可能的话,我想声明与拥有非成员函数的模板类函数的友谊。我试图与班级宣布朋友船,但失败了。  请给我解决方案或建议。非常感谢你。

#include <vector>

template <typename Derived, typename T>
class Function0 {
public:
    friend bool operator== (Derived& org, Derived& cmp) {  // ***** This line gives a warning
        Derived& org_value = static_cast<Derived&>(org);
        Derived& cmp_value = static_cast<Derived&>(cmp);
        return *(org_value.value_) == *(cmp_value.value_);
    }
};

template <typename T, template <typename Derived, typename T_T> class Functions>
class Pointer : public Functions<Pointer<T,Functions>, T> {
public:
    Pointer() {};
    Pointer(T* new_value) : value_(new_value) {};
    bool operator== (Pointer& cmp) = delete;  // ***** This line gives a warning
    virtual ~Pointer() {
};
private:
//  friend class Functions<Pointer<T,Functions>, T>;  // *** This did not work.
    friend bool operator== (Pointer<T,Functions>& org, Pointer<T,Functions>& cmp);  // *** This looks work but gave me an warning
    T* value_ = nullptr;
};

class TestA {
public:
    TestA(unsigned int id) : id_(id) {};
    virtual ~TestA() {};
    unsigned int id(void) { return id_; }

    bool operator== (TestA& cmp) {
        return (id_ == cmp.id()) ? true : false;
    }

private:
    unsigned int id_ = 0;
};

template <typename Element>
Element findCorrespondingFirst(Element& obj, std::vector<Element>& vec) {
    for (unsigned int i = 0; i < vec.size(); ++i) {
        auto o = vec[i];
        if (obj == o) {  // this dispatches an error massage
            return o;
        }
    }
    return Element();
}

void test_pointer_class(void) {

    std::vector<Pointer<TestA, Function0>> ptr_vector;

    TestA* raw_ptr0 = new TestA(1);
    TestA* raw_ptr1 = nullptr;
    TestA* raw_ptr2 = new TestA(2);

    Pointer<TestA, Function0> ptr0 = Pointer<TestA, Function0>(raw_ptr0);
    Pointer<TestA, Function0> ptr1 = Pointer<TestA, Function0>(raw_ptr1);
    Pointer<TestA, Function0> ptr2 = Pointer<TestA, Function0>(raw_ptr2);

    TestA* raw_ptr3 = new TestA(1);
    Pointer<TestA, Function0> ptr3 = Pointer<TestA, Function0>(raw_ptr3);

    ptr_vector.push_back(ptr0);
    ptr_vector.push_back(ptr1);
    ptr_vector.push_back(ptr2);
    ptr_vector.push_back(ptr3);

    auto result1 = findCorrespondingFirst(ptr3, ptr_vector);

    delete raw_ptr0;
    delete raw_ptr1;
    delete raw_ptr2;
    delete raw_ptr3;

}

来自gcc的警告信息如下:

friend declaration ‘bool operator==(Pointer<T, Functions>&, Pointer<T, Functions>&)’ declares a non-template function -[Wnon-template-friend]

0 个答案:

没有答案