Reputation: 295
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.
Upvotes: 1
Views: 673
Reputation: 8494
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 char
s 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.
Upvotes: 1