Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing const char* as template argument

Why can't you pass literal strings in here? I made it work with a very slight workaround.

template<const char* ptr> struct lols {     lols() : i(ptr) {}     std::string i; }; class file { public:     static const char arg[]; }; decltype(file::arg) file::arg = __FILE__; // Getting the right type declaration for this was irritating, so I C++0xed it.  int main() {     // lols<__FILE__> hi;      // Error: A template argument may not reference a non-external entity     lols<file::arg> hi; // Perfectly legal     std::cout << hi.i;     std::cin.ignore();     std::cin.get(); } 
like image 990
Puppy Avatar asked Sep 22 '10 20:09

Puppy


1 Answers

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.

like image 144
Johannes Schaub - litb Avatar answered Oct 09 '22 03:10

Johannes Schaub - litb