Custom String Literals
-
22-06-2021 - |
Question
Out of curiosity, I was wondering how different files are able to assign certain symbols to change they regular c-string literals into other literals.
For Example...
In Objective-C, the NSString literal can be written by @"..."
In C++ (I think), the C++ String literal is written S"..."
In the wchar library, the wchar_t literal is writtel L"..."
Can anyone tell me how to do a string like, MyClass literal as #"..."
Thanks
La solution
You can use only something like this.
#include <iostream>
#include <string>
struct MyClass
{
public:
MyClass(const char* a, size_t sz):
s(a, sz)
{
}
std::string get() const { return s; }
private:
std::string s;
};
MyClass operator "" _M(const char* arr, size_t size) { return MyClass(arr, size); }
int main()
{
MyClass c = "hello"_M;
std::cout << c.get() << std::endl;
}
C++11 allows user-defined literals. http://liveworkspace.org/code/cfff55e34d3b707e1bf0cb714e8e8f29
But there are no abilities to define prefix literals.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow