0

I have a CRTP-class, and want to perform intermediate steps with the data passed through the interface. The goal is to be able to call arbitrary method (foo or bar) in the derived class, from B.

Edit 2: The initial example avoided some of the problems with oversimplification, but this example captures the purpose.

#include <iostream>
template <typename Derived, typename RetType>
struct A;

// Pass template arguments so that:
template <typename Base, typename Derived, typename RetType, RetType (Base::*method)(void)>
struct B
{
private:
    Base *p_A_;

public:
    B(Base *p_A) : p_A_(p_A) {}

    RetType callAmethod()
    {
        return static_cast<Derived *>(p_A_)->method();
    }
};

template <typename Derived, typename RetType>
struct A
{
private:
    B<A<Derived, RetType>, Derived, RetType, &A<Derived, RetType>::foo> foo_B;
    B<A<Derived, RetType>, Derived, RetType, &A<Derived, RetType>::bar> bar_B;
public:
    RetType foo();
    RetType bar();

    A() : foo_B(this), bar_B(this) {}

};

template <typename Derived, typename RetType>
RetType A<Derived, RetType>::foo()
{
    return foo_B.callAmethod();
}
template <typename Derived, typename RetType>
RetType A<Derived, RetType>::bar()
{
    return bar_B.callAmethod();
}

struct A_Derived : public A<A_Derived, int>
{
    int foo()
    {
        return 1;
    }

    int bar()
    {
        return 2;
    }
};

int main()
{
    A_Derived obj;
    std::cout << obj.foo() << ", " << obj.bar() << std::endl;
}

I'm trying to 'inject' a struct in-between the methods of A and A_derived, so that A.method() -> B.method() -> A_Derived.method() Is this possible?

Jonas Hjulstad
  • 395
  • 1
  • 8
  • Unclear what you want, your snippet won't compile, doesn't use CRTP... – Jarod42 Oct 29 '21 at 10:45
  • 1
    Please try to create a proper [mre] to show us. – Some programmer dude Oct 29 '21 at 10:45
  • Related: [C++ inheritance and member function pointers](https://stackoverflow.com/questions/60000/c-inheritance-and-member-function-pointers). – dfrib Oct 29 '21 at 11:08
  • 1
    What do you think the line `return static_cast(p_A_)->method();` does? You cast from `Base*` to `Derived*`, but then apply a pointer-to-member of `Base`, making the cast useless (assuming `Base` is in fact a base class of `Derived`). Shouldn't that last template parameter to `B` be a pointer-to-member of `Derived` instead of `Base`, since that is how you try to call it? As in `RetType (Derived::*method)()`? – JaMiT Oct 29 '21 at 14:40
  • If the last parameter to B would have been a pointer-to-member of Derived, I would've had to pass B(this)->foo> foo_B; instead. This cast is of an unresolved type, so it doesn't allow me to pass that as a template parameter – Jonas Hjulstad Oct 29 '21 at 15:53

0 Answers0