c++ - SFINAE 检查继承的成员函数

标签 c++ templates metaprogramming sfinae

使用 SFINAE,我 can detect给定的类是否具有特定的成员函数。但是,如果我想测试继承的成员函数怎么办?

以下在 VC8 和 GCC4 中不起作用(即检测到 A 有一个成员函数 foo(),但没有 B继承一个):

#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
}

那么,有没有办法测试继承的成员函数呢?

最佳答案

看看这个线程:

http://lists.boost.org/boost-users/2009/01/44538.php

源自该讨论中链接的代码:

#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

关于c++ - SFINAE 检查继承的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5747205/

相关文章:

c++ - 对图像中的一系列颜色进行阈值处理

c++ - 用于初始化模板类的静态数据成员的部分模板特化

c++ - 如何解决以下代码中的函数重载歧义

c++ - 检测 SFINAE 的 POD 类型的第一个成员

用于在编译时确定成员数量的 C++ 宏/元程序

c++ - 如何比较 C++ 中 lambda 函数的返回类型?

c++ - 数组 [] 运算符返回一个引用,那么如何更改它的值呢?

c++ - 如何区分存储在模板类中的类型

ruby - Ruby 中的 method_missing 陷阱

c++ - 什么样的值是模板参数?我能(不能)用它们做什么?