<type_traits>的is_function_pointer <>

Nub*_*ase 10 c++ visual-studio-2010 visual-studio visual-c++ c++11

有这些<type_traits>:

is_pointer<>
is_function<>
is_member_function_pointer<>
Run Code Online (Sandbox Code Playgroud)

但不是这个:

is_function_pointer<>
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

How*_*ant 11

[meta.unary.cat]中的特征旨在将每种类型分类为单个类别.它是一个void,整数,指针等.在这个级别,指向函数的指针与指向int的指针没有什么不同.请注意,指向成员的指针不是指针.它只是一个英国的谐音.

意图是每个类型都在[meta.unary.cat]中返回真正的一个特征.在这种分类中,函数指针和标量指针都将返回true is_pointer.

我会注意到我们没有实现我们的目标. nullptr_t逃避我们的目标.但我们接近了. 以下是当前type_traits分类的图形表示.

更新:

这是一个正确工作的程序,输出正确:

#include <iostream>
#include <type_traits>

typedef void (*fptr)();
typedef int* intptr;

int main()
{
    std::cout << std::is_function<fptr>::value << '\n';
    std::cout << std::is_pointer<fptr>::value << '\n';
    std::cout << std::is_pointer<intptr>::value << '\n';
}

0
1
1
Run Code Online (Sandbox Code Playgroud)

  • 指向函数的指针实际上与`int*`非常不同.一个(`int*`)可以通过`void*'进行往返,但是函数指针不能. (2认同)
  • 我怀疑`is_function_pointer`的不存在也是因为有`remove_pointer`,这使得它可以表达为`is_pointer <T> && is_function <remove_pointer <T >>`.但对于`is_member_function_pointer`,人们需要`remove_member_pointer`,它似乎不存在.我想知道为什么呢? (2认同)

Nic*_*las 6

这似乎是一个奇怪的疏忽.但是,成员指针总是成员指针类型,与自由函数不同,自由函数可以是指针类型(void(*)())或函数类型(void()).std::is_pointer对于成员指针类型,也永远不会返回true.

但是,如果您需要此功能,请执行以下操作:

template<typename testType>
struct is_function_pointer
{
    static const bool value =
        std::is_pointer<testType>::value ?
        std::is_function<typename std::remove_pointer<testType>::type>::value :
        false;
};
Run Code Online (Sandbox Code Playgroud)