Passing const char* as template argument

Solution 1:

Because this would not be a useful utility. Since they are not of the allowed form of a template argument, it currently does not work.

Let's assume they work. Because they are not required to have the same address for the same value used, you will get different instantiations even though you have the same string literal value in your code.

lols<"A"> n;

// might fail because a different object address is passed as argument!
lols<"A"> n1 = n;

You could write a plugin for your text editor that replaces a string by a comma separated list of character literals and back. With variadic templates, you could "solve" that problem this way, in some way.

Solution 2:

It is possible, but the the template argument must have external linkage, which precludes using literal strings and mitigates the utility of doing this.

An example I have is:

template<const char* name, const char* def_value=empty_>
struct env : public std::string
{
    env()
    {
        const char* p = std::getenv(name);
        assign(p ? p : def_value);
    }
};

extern const char empty_[] = "";

std::string test = env<empty_>();

Solution 3:

This is how I do it. Makes a lot more sense to me:

struct MyString { static const std::string val; };
const std::string MyString::val = "this is your string";

template<typename T>
void func()
{
  std::cout << T::val << std::endl;
}

void main()
{
  func<MyString>();
}