Search code examples
c++typedefconstexpr

Constexpr typedef


Unfortunately you can not do something like this:

typedef constexpr int cint;

And that is not the end of the world....just have to type out the extra 9 (10 if you include the space) characters every time you need to use constexpr.

But I have created a class and I want to only be able to create constexpr versions of this class (using a non constexpr version would not make any sense).

So my plan was to create the class with a non accessible namespace, and then create in my main namespace a constexpr typedef, like so:

namespace MainNameSpace{
  namespace detail{
    class MyClass{};

  }
  typedef constexpr detail::MyClass MyClass;
}

Unfortunately I discovered that this cannot be done....is there any way to achieve a similar effect (with out using macros)?


Solution

  • typedef constexpr detail::MyClass MyClass; doesn't make much sense. You're establishing a contract that MyClass is a valid constexpr class and that you will only use it in constexpr contexts, but there is no way the compiler can guarantee that by that statement alone...it all comes down to how MyClass is implemented and what contexts you use it in. It's redundant and meaningless. If you're interested in a "compile-time string class", take a look at string_view.