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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top