【发布时间】:2019-09-06 14:46:18
【问题描述】:
如果函数在基类中实现,如何将函数指针作为模板参数传递。
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 构建它。
有什么想法吗?
附: BF bf = &B::F; 此转换无需强制转换即可工作,因此编译器理解类 B 具有方法 F。但它不能用作模板参数。
更新:P.P.S.实际的类和代码更复杂。上面的例子只是一个非常简化的版本来概述问题。
解决方法:我使用的当前解决方法是覆盖 B 类中的 F(),它只是调用继承,但仍在寻找更好的解决方案。
【问题讨论】:
-
不知道,但也许你能找到一些有趣的东西here。