简体   繁体   English

将constness添加到函数指针时会发生什么?

[英]What happens when adding constness to a function pointer?

Static assertions all fail. 静态断言全部失败。 What type is Constifier creating for 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, "");
}

The function pointer is unchanged: 函数指针不变:

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

You cannot alter a function because it lives in the code section of the memory, so you can think of a function pointer implicity pointing to const already. 您不能更改函数,因为它位于内存的代码部分中,因此您可以想到已经隐式指向const的函数指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM