SFINAE to check for inherited member functions(SFINAE 检查继承的成员函数)
问题描述
使用 SFINAE,我 可以检测给定的类是否具有某个成员函数.但是如果我想测试继承的成员函数怎么办?
Using SFINAE, i can detect wether a given class has a certain member function. But what if i want to test for inherited member functions?
以下在 VC8 和 GCC4 中不起作用(即检测到 A
具有成员函数 foo()
,而不是 B
继承一个):
The following does not work in VC8 and GCC4 (i.e. detects that A
has a member function foo()
, but not that B
inherits one):
#include <iostream>
template<typename T, typename Sig>
struct has_foo {
template <typename U, U> struct type_check;
template <typename V> static char (& chk(type_check<Sig, &V::foo>*))[1];
template <typename > static char (& chk(...))[2];
static bool const value = (sizeof(chk<T>(0)) == 1);
};
struct A {
void foo();
};
struct B : A {};
int main()
{
using namespace std;
cout << boolalpha << has_foo<A, void (A::*)()>::value << endl; // true
cout << boolalpha << has_foo<B, void (B::*)()>::value << endl; // false
}
那么,有没有办法测试继承的成员函数?
So, is there a way to test for inherited member functions?
推荐答案
看看这个线程:
http://lists.boost.org/boost-users/2009/01/44538.php
源自该讨论中链接到的代码:
Derived from the code linked to in that discussion:
#include <iostream>
template <typename Type>
class has_foo
{
class yes { char m;};
class no { yes m[2];};
struct BaseMixin
{
void foo(){}
};
struct Base : public Type, public BaseMixin {};
template <typename T, T t> class Helper{};
template <typename U>
static no deduce(U*, Helper<void (BaseMixin::*)(), &U::foo>* = 0);
static yes deduce(...);
public:
static const bool result = sizeof(yes) == sizeof(deduce((Base*)(0)));
};
struct A {
void foo();
};
struct B : A {};
struct C {};
int main()
{
using namespace std;
cout << boolalpha << has_foo<A>::result << endl;
cout << boolalpha << has_foo<B>::result << endl;
cout << boolalpha << has_foo<C>::result;
}
结果:
true
true
false
这篇关于SFINAE 检查继承的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SFINAE 检查继承的成员函数
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07