向函数指针添加constness时会发生什么

What happens when adding constness to a function pointer?

本文关键字:什么 constness 函数 指针 添加      更新时间:2023-10-16

静态断言都失败。什么类型是Constifier创建一个函数指针?

#include <type_traits>
template<typename T>
struct Constifier;
template<typename T>
struct Constifier<T *>
{
    typedef const T *Type;
};
int main()
{
    static_assert(std::is_same<typename Constifier<int (*)()>::Type, const int (*)()>::value, "");
    static_assert(std::is_same<typename Constifier<int (*)()>::Type, int (*const)()>::value, "");
    static_assert(std::is_same<typename Constifier<int (*)()>::Type, void>::value, "");
}

函数指针不变:

static_assert(std::is_same<typename Constifier<int (*)()>::Type, int (*)()>::value, "");

你不能改变一个函数,因为它存在于内存的代码区,所以你可以认为函数指针隐式地指向const。