如何通过C++模板函数返回指定类的成员变量?
问题分析与修复
你的错误核心是混淆了成员指针和成员变量的值:模板参数x的类型是U T::*(指向T类型中U类型成员的指针),而你直接返回x相当于返回这个指针本身,不是变量的实际值,类型自然不匹配。
修复后的代码
只需要修改函数内部的返回语句,通过对象t访问成员指针指向的变量,语法为t.*x:
template<typename T, typename U, U T::* x> U testFunc(T& t) { // 访问对象t中成员指针x指向的变量并返回其值 return t.*x; } struct testS1 { int a = 100; }; struct testS2 { bool b = true; }; testS1 tS1; testS2 tS2; // 返回100 int c = testFunc<testS1, int, &testS1::a>(tS1); // 返回true bool d = testFunc<testS2, bool, &testS2::b>(tS2);
优化写法(简化调用)
可以让编译器自动推导U的类型,不用手动指定,调用时更简洁:
template<typename T, typename U, U T::* x> U testFunc(T& t) { return t.*x; } // 调用时省略U模板参数,由编译器推导 int c = testFunc<testS1, &testS1::a>(tS1); bool d = testFunc<testS2, &testS2::b>(tS2);
这种方案完全不需要基类,能适配任意结构差异的类型,符合游戏引擎通用函数的需求。
内容的提问来源于stack exchange,提问作者ModernEraCaveman
相关产品推荐
相关产品推荐

