2

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.

6
  • 1
    Yes, but it is not terribly helpful because it doesn't behave as you would expect (it uses pointer equality, not string equality). Commented Jul 11, 2013 at 15:40
  • Well... you could probably make a variadic template that takes in a bunch of characters as template inputs. At least it would give you real string equivalence. std::string will not work though because template arguments must be integral types. Commented Jul 11, 2013 at 15:59
  • Possible duplicate of Strings as template arguments?. See also Non-type template parameters Commented Jul 11, 2013 at 16:01
  • @Aggieboy Or pointers or references to objects with external linkage. (String literals don't work because they don't have external linkage.) Commented Jul 11, 2013 at 16:07
  • @JamesKanze Ahh details; a reference is just a pointer, a pointer is just an int, and an int is an integral. XD Commented Jul 11, 2013 at 16:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.