c++ - 类成员函数在继承的情况下作为模板参数
问题描述
如果函数在基类中实现,如何将函数指针作为模板参数传递。
template<class T, int(T::* FUNC)() const>
int TestFunc(const T& _v)
{
return (_v.*FUNC)();
}
struct A
{
int F() const { return 100; }
};
struct B : public A {};
int main()
{
B b;
int32_t value = TestFunc<B, &B::F>(b);
cout << value;
//...
}
收到错误 C2672:“TestFunc”:未找到匹配的重载函数。
如果 VS 编译器 static_cast 有帮助:
typedef int(B::* BF)() const;
int32_t value = TestFunc<B, static_cast<BF>(&B::F)>(b);
这些已成功构建并运行,但我需要使用 clang 构建它。
有任何想法吗?
PSBF bf = &B::F;
这种转换没有强制转换,所以编译器理解 class B
has method F
。但它不能用作模板参数。
更新:PPS 实际类和代码更复杂。上面的例子只是一个非常简化的版本来概述问题。
解决方法:我使用的当前解决方法是覆盖 B 类中的 F() ,它只是调用继承,但仍在寻找更好的解决方案。
解决方案
一种选择是仅用A
作模板参数:
int32_t value = TestFunc<A, &A::F>(b);
推荐阅读
- asp.net-mvc - 在我的操作中使用 TempData 时发生序列化错误
- odbc - Julia ODBC 连接在 Jupyter 中产生弹出窗口
- sql - 如何插入 sql 并跳过已经存在的内容?
- symfony - 模板中不存在变量实体,如何解决?
- python - 第一次点击后如何将可点击的 QLineEdit 变成普通的?
- css - 当字段是原始的时,如何不触发 ng-pattern?
- c# - 用于打字游戏的波生成器和波数
- php - php count 返回 1 而不是真正的数组长度
- fiddler - Fiddler 代理不适用于 https 请求
- .net - 使用 Jenkins 将点网项目部署到 AWS Lambda