Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Literal As Template Argument

Tags:

c++

templates

These preprocessor and template limitations of c++ are killing me. The goal is to convert string literals into integers.

template<const char* str>
inline int LiteralToInt(){
    return __COUNTER__;
}

using std::cout;

int main(){
    cout << LiteralToInt<"Hello">();
    cout << LiteralToInt<"No">();
    cout << LiteralToInt<"Hello">();
    return 0;
}

The output would be 010 if templates accepted string literals. Is there another way to get this output and convert string literals to integers at compile time?

like image 601
user936509 Avatar asked Feb 18 '26 04:02

user936509


2 Answers

Yes, C++ 11's constexpr will do this for you:

 constexpr int LiteralToInt(const char * str) {
      return __COUNTER__; // or whatever.
 }
like image 89
Richard J. Ross III Avatar answered Feb 20 '26 18:02

Richard J. Ross III


Something like this would work

extern const char HELLO[] = "Hello";

and then

cout << LiteralToInt<HELLO>();

but not the literal itself. This is probably not what you want.

String literals themselves, as you already discovered, cannot be used as template arguments.

like image 26
AnT Avatar answered Feb 20 '26 18:02

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!