类成员的模板参数

Template parameter of class member

本文关键字:参数 成员      更新时间:2023-10-16

使用模板可以实现这样的功能吗?

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;
}

我已经知道如何使用宏

#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;
}

如果我正确理解您的意图,那么以下内容应该有效:

#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';
}

在线演示