Passing a string literal as a parameter to a C++ template class


Question

I want a class which takes two parameters in its constructor. The first can be either an int, double or float, so <typename T>, and the second is always a string literal "my string", so I guess const char * const.

Can anyone give me some compilable code which declares a simple class template as described and declares an object of that class?

Thanks

1
37
12/5/2017 7:25:25 PM

Accepted Answer

Sorry, C++ does not currently support the use of string literals (or real literals) as template parameters.

But re-reading your question, is that what you are asking? You cannot say:

foo <"bar"> x;

but you can say

template <typename T>
struct foo {
   foo( T t ) {}
};

foo <const char *> f( "bar" );
22
1/9/2010 11:04:32 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon