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?
Yes, C++ 11's constexpr will do this for you:
constexpr int LiteralToInt(const char * str) {
return __COUNTER__; // or whatever.
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With