Reputation: 13575
Is it possible to make a string as a template parameter and how? Like
A<"Okay"> is a type.
Any string (std::string or c-string) is fine.
Upvotes: 2
Views: 166
Reputation: 2524
Here's one way to make the string contents determine uniqueness
#include <windows.h> //for Sleep()
#include <iostream>
#include <string>
using namespace std;
template<char... str>
struct TemplateString{
static const int n = sizeof...(str);
string get() const {
char cstr[n+1] = {str...}; //doesn't automatically null terminate, hence n+1 instead of just n
cstr[n] = '\0'; //and our little null terminate
return string(cstr);
}
};
int main(){
TemplateString<'O','k','a','y'> okay;
TemplateString<'N','o','t',' ','o','k','a','y'> notokay;
cout << okay.get() << " vs " << notokay.get() << endl;
cout << "Same class: " << (typeid(okay)==typeid(notokay)) << endl;
Sleep(3000); //Windows & Visual Studio, sry
}
Upvotes: 1
Reputation: 153899
Yes, but you need to put it in a variable with external linkage (or does C++11 remove the requirement for external linkage). Basically, given:
template <char const* str>
class A { /* ... */ };
this:
extern char const okay[] = "Okay";
A<okay> ...
works. Note thought that it is not the contents of the string which define uniqueness, but the object itself:
extern char const okay1[] = "Okay";
extern char const okay2[] = "Okay";
Given this, A<okay1>
and A<okay2>
have different types.
Upvotes: 2