Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ instantiate function template as class member and using "this" pointer

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

Is this impossible because of that limitation? Or is there some way to use "this" inside of a function template that is not declared as part of a template class. I've done 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

classB is similar.

Any help is appreciated!

like image 721
matjoeman Avatar asked Dec 19 '25 17:12

matjoeman


1 Answers

I believe you can use CRTP here. Here is an example, you can omit the friend declaration in case you can do the compare using only public members:

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;
}
like image 189
Naveen Avatar answered Dec 22 '25 06:12

Naveen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!