2

I have the following function defined in a header file :

uint32_t get_id(void) const { return m_id; }

I want to enforce a rule that whichever function calls the above function should add constantness to the value returned , as in :

const uint32_t = const_cast(get_id);

Is that possible in C++ ?

001
  • 13,291
  • 5
  • 35
  • 66

1 Answers1

1

No, you cannot do that for uint32_t.

What you could do would be to define a class that prohibited any modification (and containing the uint32_t as a private member) and return an object of that class.

This includes making T operator=(const T&) non-callable (private or =delete), see e.g. What is The Rule of Three?

You would still need a method for extracting the underlying uint32_t - but at least you would avoid accidental changes of the returned value - if that was the underlying issue you tried to solve.

Hans Olsson
  • 11,123
  • 15
  • 38
  • Note that nothing would prevent copying that class, and that the returned `uint32_t` cannot be modified in-place anyway. So I can't see how this would help. – Angew is no longer proud of SO Mar 01 '18 at 15:11
  • By prohibiting modifications of objects of the class, it could prevent "auto x=get_id(); x=get_id(); " and "auto x=get_id(); x++;" - similarly as if x were const. Why someone would want that I don't know. – Hans Olsson Mar 01 '18 at 15:33
  • @Angew .... So, if someone were to copy this class, they would be able to modify the returned value ? –  Mar 05 '18 at 04:43
  • @anju.gopinath Well, if the class prevents modification, then no. But either you must not offer a way of extracting the `uint32_t`, or anyone can get that value and then modify it to their heart's content. They could even do `uint32_t x = get_id().getValue();`. Which is why I claim this cannot be reasonably answered without knowing the underlying motivation. – Angew is no longer proud of SO Mar 05 '18 at 08:00