将常量添加到函数指针时会发生什么?
What happens when adding constness to a function pointer?
静态断言全部失败。 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。
静态断言全部失败。 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。