N
N
no111u32017-10-21 16:56:29
C++ / C#
no111u3, 2017-10-21 16:56:29

C++11 how to make the calculation of the address in the pointer to the structure happen at compile time?

There is a code sample that successfully builds on GCC up to 6.1, but does not build on GCC 6.3 and does not build on any version of Clang.

constexpr int * const t = reinterpret_cast<int *>(0x40000);


template <int addr>
class C {
public:
  struct gpio_t {
    int test;
  };
  static constexpr volatile gpio_t * const regs =
    reinterpret_cast<volatile gpio_t *>(addr);
};

int main() {
  C<0x40000000>::regs->test = 5;
}

During the excavations, I realized that this comes from the fact that any manipulations with address arithmetic are prohibited in the standard itself, hence the question followed, how to make it comply with the standard without changing the efficiency and safety of the code.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Mikhailuts, 2018-05-19
@JBMurloc

If I understand correctly, then all these perversions are only to work with an arbitrary address in memory, as with a structure field. In this regard, the question is why not just do this:

struct gpio_t {
    int test;
  };

#define TEST_1 reinterpret_cast<volatile gpio_t *> (0x12345678)

int main() {
TEST_1->test = 5;
}

In theory it should work. In any case, such tricks worked for me.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question