首页 > 解决方案 > 类成员函数在继承的情况下作为模板参数

问题描述

如果函数在基类中实现,如何将函数指针作为模板参数传递。

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 Bhas method F。但它不能用作模板参数。

更新:PPS 实际类和代码更复杂。上面的例子只是一个非常简化的版本来概述问题。

解决方法:我使用的当前解决方法是覆盖 B 类中的 F() ,它只是调用继承,但仍在寻找更好的解决方案。

标签: c++templatesc++14

解决方案


一种选择是仅用A作模板参数:

int32_t value = TestFunc<A, &A::F>(b);

推荐阅读