DarthRubik
DarthRubik

Reputation: 3985

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)?

Upvotes: 2

Views: 2910

Answers (2)

Baptistou
Baptistou

Reputation: 2121

This could be possible in C++20 with consteval specifier.

I can't run a test yet but I think that you could either write immediate constructors in MyClass or write an immediate function which create an instance of MyClass as constant expression only.

//immediate constructors
class MyClass {
    consteval MyClass();
    consteval MyClass(const MyClass&);
};

//OR immediate instantation function
consteval MyClass make_myclass();

Upvotes: 0

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.

Upvotes: 2

Related Questions