I want to declare a class template in which one of the template parameters takes a string literal, e.g. my_class<"string">
.
Can anyone give me some compilable code which declares a simple class template as described?
Note: The previous wording of this question was rather ambiguous as to what the asker was actually trying to accomplish, and should probably have been closed as insufficiently clear. However, since then this question became multiple times referred-to as the canonical ‘string literal type parameter’ question. As such, it has been re-worded to agree with that premise.
A string literal cannot be used as a template argument.
If you want to pass the string literal "directly" (without constructing an std::string), the most common way is to pass the pointer to it. This code is also legal: const int& ten = 10; Is the compiler simply replacing the reference with the literal wherever it appears?
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, for string interpolation with embedded expressions, and for special constructs called tagged templates.
Is there any way to print the contents of the String literal pool? String literals passed as arguments are also String literals, so: yes. Why would they be any different? This all happens when the String is created.
You can have a const char*
non-type template parameter, and pass it a const char[]
variable with static
linkage, which is not all that far from passing a string literal directly.
#include <iostream> template<const char *str> struct cts { void p() {std::cout << str;} }; static const char teststr[] = "Hello world!"; int main() { cts<teststr> o; o.p(); }
http://coliru.stacked-crooked.com/a/64cd254136dd0272
Further from Neil's answer: one way to using strings with templates as you want is to define a traits class and define the string as a trait of the type.
#include <iostream> template <class T> struct MyTypeTraits { static const char* name; }; template <class T> const char* MyTypeTraits<T>::name = "Hello"; template <> struct MyTypeTraits<int> { static const char* name; }; const char* MyTypeTraits<int>::name = "Hello int"; template <class T> class MyTemplateClass { public: void print() { std::cout << "My name is: " << MyTypeTraits<T>::name << std::endl; } }; int main() { MyTemplateClass<int>().print(); MyTemplateClass<char>().print(); }
prints
My name is: Hello int My name is: Hello
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With