1

I am aware that the new C++ standard allows for user-defined literals and that their generation can be done in compile time.

However, I am quite new to the whole template metaprogramming universe and I'm trying to get some examples going, but still without success, since it's the first time I have contact with this particular feature.

So let's say I have a string:

std::string tmp = "This is a test message";

And I would like to encrypt it at compile time using:

std::string tmp = "This is a test message"_encrypt;

Is it even possible what I'm trying to attempt?

I am currently using VS2015 so any help or feedback is appreciated.

pabloxrl
  • 285
  • 2
  • 12
  • `std::string` is not a literal type, so you can't use `constexpr` with it. The 'encryption' won't happen compile-time, but rather at program start. – sp2danny Jul 31 '15 at 12:48
  • @sp2danny, what if I would use `const char*` instead? – pabloxrl Jul 31 '15 at 12:55
  • Well, if encrypt returned a constexpr string type like a string_view i think it should work. You might have to still cast to a std::string though. `std::experimental::string_view operator""_encrypt(const char *);` or `std::experimental::string_view operator""_encrypt(const char *, size_t);`. I can't remember if string_view has a str() member or not. – emsr Aug 01 '15 at 21:18

1 Answers1

1

Is it even possible what I'm trying to attempt?

Yes, it is possible*. What you can pre-compute and put directly in the source code can also be done by the compiler at compile time.

However, you cannot use std::string. It's not a literal type. Something like:

 constexpr std::string tmp = "some string literal"

will never compile because std::string and std::basic_string in general have no constexpr constructor.

You must therefore use const char [] as input for your meta-programming; after that, you may assign it to a std::string.
NB: Meta-programming has some restrictions you need to take into account: you don't have access to many tools you'd otherwise have, like new or malloc, for example: you must allocate on the stack your variables.


*Edit: Not entirely with UDLs, as @m.s. points out. Indeed, you receive a pointer to const chars and the length of the string. This is pretty restrictive in a constexpr scenario, and I doubt it's possible to find a way to work on that string. In "normal" meta-programming, where you can have a size that is a constant expression, compile-time encryption is instead possible.

edmz
  • 8,220
  • 2
  • 26
  • 45