如何檢查會員功能是否存在,是否不是繼承?檢查會員功能是否存在,是否繼承SFINAE
我需要這解決歧義爲以下示例:
A型或者具有一個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
@ Jarod42簽名是你寫的,但是它是一個模板函數,所以它的需要是通用的 –