【问题标题】:What happens when adding constness to a function pointer?向函数指针添加常量时会发生什么?
【发布时间】:2015-09-06 19:08:50
【问题描述】:

静态断言全部失败。 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, "");
}

【问题讨论】:

  • 在您的 trait 中,您不是将常量添加到 function pointer 而是添加到 pointed 函数,而是函数类型上的顶级 cv 限定符被忽略(虽然你可以有一个指向函数的 const 指针,然后你会使用typedef T * const Type)。顺便提一句。您在这里不需要typename 关键字。
  • @PiotrSkotnicki 我明白了,它不是依赖类型。

标签: c++ templates typetraits


【解决方案1】:

函数指针不变:

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

您无法更改函数,因为它位于内存的代码部分,因此您可以认为函数指针已经隐式指向 const。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多