Mehlins Mehlins - 1 year ago 158
C++ Question

C++: Reference 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
but for vector
. To do this there are two obvious solutions:

  • Pass vector
    as argument. However,
    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
    and use vector
    , which would be the best alternative, despite the fact that
    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

Answer Source

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)` */ }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download