类成员的模板参数
Template parameter of class member
使用模板可以实现这样的功能吗?
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';
}
在线演示
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 如何将lambda作为模板类的成员函数参数
- 将成员函数指针作为参数传递给模板方法
- c++构造函数成员初始化:传递参数
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 模板化检查是否存在带有参数列表的类成员函数?
- 如何将类成员方法的参数列表自动填充写入可变参数?
- 为什么我需要在成员发起器列表中重复基类的模板参数?
- C++向量默认为成员参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 绑定到可变参数成员函数
- C/C++ 包含点的宏参数(成员访问运算符)
- 将const char * const参数成员分配给新值
- 基于模板参数成员函数参数的模板专用化
- 如何访问可变参数成员
- 可变类参数成员变量的异构存储
- 非模板类中的可变参数成员