如何专门化模板类中的成员函数类型

How to specialize for member function type in template class?

本文关键字:成员 函数 类型 专门化      更新时间:2023-10-16

我刚刚测试了以下代码,我发现std::is_function不接受成员函数类型。(我不确定这是否适用于其他编译器,我使用MVC++ 2012年11月CTP)

   class Ac {
    public:
      float af(int) {}
    };
    int main() {
     std::cout <<  std::is_function<decltype(Ac::af)>::value << 'n'; //output is 0
    }

所以我试着实现它:

template<typename T>
struct is_member_function : std::false_type {};
template<typename T, typename R, typename... Args>
struct is_member_function<R (T::) (Args...)> : std::true_type {}; //this doesn't compile

对于成员函数指针类型,可以专门化此签名:R (T::*)(Args...),但是成员函数类型对应的语法是什么?

通过这个链接,似乎下面的实现用于is_member_function_pointer

template< class T >
struct is_member_function_pointer_helper : std::false_type {};
template< class T, class U> 
struct is_member_function_pointer_helper<T U::*> : std::is_function<T> {};
template< class T >
struct is_member_function_pointer : is_member_function_pointer_helper<
                                        typename std::remove_cv<T>::type
                                    > {};

因此,可以使用T U::*来确定某个对象是否是U类型对象的成员指针,还可以确定T是否是函数类型。我不知道成员函数类型的语法,只知道成员函数指针类型。我得查一下标准,看看这种类型是否存在。

如果这是不存在的情况下,你可以实现一个包装类添加指针为您喜欢。

template<class T>
struct is_member_function {
    static const bool value = std::is_member_function_pointer<T*>::value;
};

但是当我尝试decltype(some_type::some_member)时,我得到一个错误说我不能只使用some_type::some_member。'&'是必需的

下面的操作适用于函数成员指针

std::is_member_function_pointer<decltype(&foo::hello)>::value

在我看来,你只能使用成员指针,而不仅仅是成员类型。

上述is_member_function_pointer_helper的另一种实现可能类似于

template<class... Args, class R, class U>
struct is_member_function_pointer_helper<R (U::*)(Args...)> : std::true_type {};