【发布时间】:2016-06-13 12:34:16
【问题描述】:
如果使用静态多态性,尤其是在模板中(例如使用策略/策略模式),可能需要调用基函数成员,但您不知道实例化的类实际上是否从该基派生。
这可以很容易地用旧的 C++ 省略号重载技巧来解决:
#include <iostream>
template <class I>
struct if_derived_from
{
template <void (I::*f)()>
static void call(I& x) { (x.*f)(); }
static void call(...) { }
};
struct A { void reset() { std::cout << "reset A" << std::endl; } };
struct B { void reset() { std::cout << "reset B" << std::endl; } };
struct C { void reset() { std::cout << "reset C" << std::endl; } };
struct E: C { void reset() { std::cout << "reset E" << std::endl; } };
struct D: E {};
struct X: A, D {};
int main()
{
X x;
if_derived_from<A>::call<&A::reset>(x);
if_derived_from<B>::call<&B::reset>(x);
if_derived_from<C>::call<&C::reset>(x);
if_derived_from<E>::call<&E::reset>(x);
return 0;
}
问题是:
- 有没有更好的简单方法(例如 SFINAE 看起来不是这样)在 C++11/C++14 中实现相同的结果?
- 优化编译器会省略省略号参数函数的空调用吗?希望这种情况对任何“正常”功能都不是特别的。
【问题讨论】: