Thomas Eding
Thomas Eding

Reputation: 1

Template parameter of class member

Is something like this possible using templates?

template<class T, int T::M>
int getValue (T const & obj) {
    return obj.M;
}

class NotPlainOldDataType {
public:
    ~NotPlainOldDataType () {}
    int x;
}

int main (int argc, char ** argv) {
    typedef NotPlainOldDataType NPOD;
    NPOD obj;

    int x = getValue<NPOD, NPOD::x>(obj);

    return x;
}

I already know how to do this using macros

#define GET_VALUE(obj, mem) obj.mem

class NotPlainOldDataType {
public:
    ~NotPlainOldDataType () {}
    int x;
}

int main (int argc, char ** argv) {
    NotPlainOldDataType obj;

    int x = GET_VALUE(obj, x);

    return x;
}

Upvotes: 1

Views: 125

Answers (1)

ildjarn
ildjarn

Reputation: 62975

If I understand your intent correctly then the following should work:

#include <iostream>

template<typename T, int (T::*M)>
int getValue(T const& obj)
{
    return obj.*M;
}

class NotPlainOldDataType
{
public:
    explicit NotPlainOldDataType(int xx) : x(xx) { }
    ~NotPlainOldDataType() { }
    int x;
};

int main()
{
    typedef NotPlainOldDataType NPOD;

    NPOD obj(3);
    std::cout << getValue<NPOD, &NPOD::x>(obj) << '\n';
}

Online demo

Upvotes: 7

Related Questions