Search code examples
c++templatesreferencemember-variables

C++: Reference/pointer to member variable as template parameter


To start, I have something like this:

class Test {
    std::vector<int> a, b;
    void caller(...) { callee(...); }
    void callee(...) { /* Do stuff with 'a' */ }
}

What I wanted is to have a function that does exactly the same as callee but for vector b. To do this there are two obvious solutions:

  • Pass vector a or b as argument. However, callee is a recursive function that can go for hundreds of calls, and passing the vectors as arguments would just be unnecessary overhead.
  • Copy the function callee and use vector b, which would be the best alternative, despite the fact that callee is quite a long function and I would have a lot of duplicate code.

Out of curiosity, I went looking for the templates part and I noticed that can be used for

lvalue reference type

pointer type

pointer to member type

So I tried to do this:

class Test {
    std::vector<int> a, b;
    void caller(...) { callee<a>(...); }
    template <std::vector<int> &x> void callee(...) { /* Do stuff with 'x' */ }
}

but I get

error: use of ‘this’ in a constant expression

Is there any way to achieve this either with a reference or a pointer?

By the way, what I want can be seen as a function-scoped #define


Solution

  • Arrays and even tuples, but no love for good old pointers-to-members ?

    class Test {
        std::vector<int> a, b;
    
        void caller(/*...*/) { callee<&Test::a>(/*...*/); }
    
        template <std::vector<int> Test::*vec>
        void callee(/*...*/) { /* Do stuff with `(this->*vec)` */ }
    };