能够在C++编译时创建和操作字符串有几个有用的应用程序.尽管可以在C++中创建编译时字符串,但是该过程非常麻烦,因为字符串需要声明为可变字符序列,例如
using str = sequence<'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'>;
Run Code Online (Sandbox Code Playgroud)
诸如字符串连接,子字符串提取等许多操作可以很容易地实现为对字符序列的操作.是否可以更方便地声明编译时字符串?如果没有,是否有一个提案可以方便地声明编译时字符串?
理想情况下,我们希望能够如下声明编译时字符串:
// Approach 1
using str1 = sequence<"Hello, world!">;
Run Code Online (Sandbox Code Playgroud)
或者,使用用户定义的文字,
// Approach 2
constexpr auto str2 = "Hello, world!"_s;
Run Code Online (Sandbox Code Playgroud)
哪里decltype(str2)有一个constexpr构造函数.方法1的混乱版本可以实现,利用您可以执行以下操作的事实:
template <unsigned Size, const char Array[Size]>
struct foo;
Run Code Online (Sandbox Code Playgroud)
但是,数组需要有外部链接,所以要使方法1起作用,我们必须编写如下内容:
/* Implementation of array to sequence goes here. */
constexpr const char str[] = "Hello, world!";
int main()
{
using s = string<13, str>;
return 0; …Run Code Online (Sandbox Code Playgroud) 我想要一个编译时字符串加密,这样我就可以在我的代码中编写:
const auto encryptedInvalidLicense = ENCRYPT("Invalid license");
std::cout << encryptedInvalidLicense.decrypt() << std::endl; // outputs "Invalid license"
Run Code Online (Sandbox Code Playgroud)
并且字符串"Invalid license"不会出现在二进制文件中.预构建可能是答案,但我正在寻找一个纯c ++ constexpr解决方案来解决这个问题,它将得到VS2015的支持.
有什么建议?
我已经研究过编译时字符串加密,它没有为问题提供constexpr解决方案.
我还研究了http://www.unknowncheats.me/forum/c-and-c/113715-compile-time-string-encryption.html.虽然它是一个constexpr解决方案,但VS2015仍然将字符串纯文本添加到二进制文件中.