【发布时间】:2016-07-13 08:01:10
【问题描述】:
如何检查成员函数是否存在并且不被继承?
我需要这个来解决以下示例的歧义:
一个类型要么有一个foo() 要么有一个bar() 成员函数。 Caller 将 call 为给定类型存在的那个。然而,DerivedWithBar 从BaseWithFoo 继承foo(),但定义了自己的bar()。因此,Caller 不知道调用哪个函数。
我需要一种方法让非继承的 foo 优先于继承的 bar(),但我不知道如何检查成员函数是否被继承。
#include <iostream>
struct BaseWithFoo
{
template <typename T> void foo(T&&){std::cout << "Base::foo" << std::endl;}
};
struct DerivedWithBar : public BaseWithFoo
{
template <typename T> void bar(T&&){std::cout << "DerivedWithBar::bar" << std::endl;}
};
struct DerivedWithFoo : public BaseWithFoo
{
template <typename T> void foo(T&&){std::cout << "DerivedWithFoo::foo" << std::endl;}
};
struct EmptyDerived : public BaseWithFoo {};
struct BaseWithBar
{
template <typename T> void bar(T&&){std::cout << "BaseWithBar::bar" << std::endl;}
};
struct Caller
{
template <typename T>
auto call(T&& x) -> decltype(x.foo(*this), void())
{
x.foo(*this);
}
template <typename T>
auto call(T&& x) -> decltype(x.bar(*this), void())
{
x.bar(*this);
}
};
int main()
{
Caller c;
c.call(BaseWithFoo());
c.call(DerivedWithFoo());
c.call(DerivedWithBar());
c.call(EmptyDerived());
c.call(BaseWithBar());
}
想要的输出:
Base::foo
DerivedWithFoo::foo
DerivedWithBar::bar
Base::foo
BaseWithBar::bar
【问题讨论】:
-
你知道要测试的函数的签名(
void U::foo(Caller&))吗? -
@Jarod42 签名和你写的一样,但是它是一个模板函数,所以它需要是通用的
标签: c++ templates c++14 sfinae