C ++ instance of a function template as a member of a class and using the "this" pointer

I have two classes (ClassA and ClassB) that have two methods (comparison and convergence). These methods work in exactly the same way, but these classes are not polymorphically related (for good reason). I would like to define a function template that both of these classes can explicitly instantiate as a member, but I get errors because the methods use "this", and when I turn them into a template, the compiler throws an error because they are not member functions.

Is this really impossible because of this limitation? Or is there a way to use "this" inside a function template that is not declared as part of the template class. I did some research and found nothing.

Logic.h

template <class T>
T* compare(const T& t) {
//stuff involving this
}

template <class T>
T* converge(const T& t,bool b) {
//other stuff involving this
}

ClassA.cpp

#include "ClassA.h"
#include "Logic.h"
//constructors

template ClassA* ClassA::compare(const ClassA& t) const; 
template ClassA* ClassA::converge(const ClassA& t,bool b) const;
//other methods

class B is similar.

!

+3
3

, CRTP. , friend , , :

template<class T>
class comparer
{
public:
    T* compare(const T& t)
    {
        //Use this pointer
        bool  b =  static_cast<T*>(this)->m_b  == t.m_b;
        return NULL;
    }
};

class A : public comparer<A>
{
public:
    friend class comparer<A>;
    A() : m_b(0)
    {
    }

private:
    int m_b;
};

class B : public comparer<B>
{
public:
    friend class comparer<B>;
    B() : m_b(0)
    {
    }

private:
    int m_b;
};

int main()
{
    A a1,a2;
    A* p = a1.compare(a2);

    B b1,b2;
    B* p1 = b1.compare(b2);

    return 0;
}
+2

, . , A classB. A classB, , .

template <typename T>
bool compare(const T& t1, const T& t2)
{
    return t1.val == t2.val;
}

class A
{
public:
    template <typename T>
    friend bool compare(const T&, const T&);

    bool compare(const A& a)
    {
        return ::compare(*this, a);
    }

private:
    int val;
};

A a1, a2;
a1.compare(a2);
0

, , . . -, -.

() ? , . STL (, BTW, ++), , , , OO , - . , :

, -, , , . . , .

0
source

Source: https://habr.com/ru/post/1765242/


All Articles