2

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

Chase Walden
  • 1,252
  • 1
  • 14
  • 31
  • These are implemented into C++. The `S""` one doesn't exist as far as I know; `L""` is predefined to mean a wide-character literal. However, C++11 implements [user-defined literals](http://www2.research.att.com/~bs/C++0xFAQ.html#UD-literals). Even then, they can only go at the end, and anything not beginning with an underscore is reserved, IIRC. – chris Jul 20 '12 at 03:01
  • Where is the L"" defined? PS Maybe the S"" is c# – Chase Walden Jul 20 '12 at 03:06
  • It's not in any of the headers; it's in the language itself, just like `int`, and all other keywords. – chris Jul 20 '12 at 03:07
  • so does the c compiler just assume that wchar exists? – Chase Walden Jul 20 '12 at 03:07
  • Not exactly too familiar with preprocessor techniques, but I think you can probably implement something with the preprocessor that works somewhat similar to a custom literal. – TheAmateurProgrammer Jul 20 '12 at 03:08
  • @ChaseWalden, From the standard: `A character literal that begins with the letter L, such as L’x’, is a wide-character literal. A wide-character literal has type wchar_t.` It's also a keyword, and a simple type specifier, which includes `int`, `double`, etc. – chris Jul 20 '12 at 03:14
  • So the compiler turns L"" into a int * – Chase Walden Jul 20 '12 at 03:19
  • It turns it into a `const wchar_t[]`, actually, just as `""` is a `const char[]`. – chris Jul 20 '12 at 03:20

1 Answers1

4

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.

ForEveR
  • 55,233
  • 2
  • 119
  • 133