2

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

6
  • 5
    constexpr isn't part of the type system. It's part of the expression system, i.e. of the nature of values. Commented May 29, 2016 at 0:33
  • @KerrekSB I discovered that the hard way Commented May 29, 2016 at 0:34
  • 3
    using a non constexpr version would not make any sense How does a constexpr version make sense? What do you expect it to do? Commented May 29, 2016 at 0:35
  • @deviantfan I have designed a class specifically for compile time strings...if I wanted to use the non-constexpr version I was probably trying to use a normal string or I just forgot to type it out.....I am wondering if there is any way to avoid this mistake Commented May 29, 2016 at 0:37
  • @DarthRubik: "if I wanted to use the non-constexpr version I was probably trying to use a normal string" Why? A static string would presumably not allocate heap space. That sounds like a good reason to want to use one even at runtime, where reasonable. Commented May 29, 2016 at 1:05

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.