constexpr constexpr函数指针的数组

时间:2020-04-30 06:55:20

标签: c++ c++11

我正在努力了解constexpr的工作方式。而且我需要将很多代码从const转换为constexpr。但是我遇到了一个我看不到解决方案的问题。

我有以下课程:

class Control_base
{
public:

  static constexpr Control_base high_clock();

  static constexpr uint8_t size();

  static const Control_base from_index(uint8_t index_);

  Control_base& operator=(const Control_base& rhs) = default;

  constexpr Device_address value() const;
private:
  constexpr explicit Control_base(Device_address value_);

  Device_address value;


};

constexpr Control_base::Control_base(Device_address value_) :
  value(value_) {}

constexpr Device_address Control_base::value() const { return value; }

inline const Control_base Control_base::high_clock() { return Control_base(reinterpret_cast<Device_address>(0x10009000)); }

typedef const Control_base (*Control_base_func)(void);

const Control_base_func Control_base_arr[] = {&Control_base::high_clock};

inline const Control_base Control_base::from_index(uint8_t index_)
{
  return Control_base_arr[index_]();
}

constexpr uint8_t Control_base::size() { return 1; }

};

我希望进行以下更改:

来自

inline const Control_base Control_base::high_clock() { return Control_base(reinterpret_cast<Device_address>(0x10009000)); }

typedef const Control_base (*Control_base_func)(void);

const Control_base_func Control_base_arr[] = {&Control_base::high_clock};

收件人

constexpr Control_base Control_base::high_clock() { return Control_base(reinterpret_cast<Device_address>(0x10009000)); }

typedef const Control_base (*Control_base_func)(void);

constexpr Control_base_func Control_base_arr[] = {&Control_base::high_clock};

但是,我在

中遇到以下错误
constexpr Control_base_func Control_base_arr[] = {&Control_base::high_clock};
                                                  ^

**value of type "ns::Control_base (*)()" cannot be used to initialize an entity of type "const ns::Control_base_func"**

我不知道这里是最好的解决方案。以及为什么它可以使用const但不能使用constexpr

致谢

1 个答案:

答案 0 :(得分:0)

解决了这个问题,我忽略了将返回类型从const更改为non-const

它应该看起来像这样

constexpr const Control_base Control_base::high_clock() { return Control_base(reinterpret_cast<Device_address>(0x10009000)); }

typedef const Control_base (*Control_base_func)(void);

constexpr Control_base_func Control_base_arr[] = {&Control_base::high_clock};

致谢