I have two questions about friend declaration in the following code. (1) I declared a friend function. The program looks working but I got a warning from compiler. The original function is a non-member function defined in a class by friend declaration. Do I need to care of it? Or do I have problem? (2) If possible, I would like to declare friendship with the template class Functions which owns the non-member function. I tried to declare friend ship with the class but it failed. Please give me solution or suggestions. Thank you very much.
#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;
}
The warning message from gcc is following,
friend declaration ‘bool operator==(Pointer<T, Functions>&, Pointer<T, Functions>&)’ declares a non-template function -[Wnon-template-friend]