While writing code for wrapping Lua, I came across the need for passing string literals and started to wonder which way it is the most efficient.
I have the choice between two functions:
void lua_pushstring (lua_State* L, const char* str);void lua_pushlstring(lua_State* L, const char* str, size_t len);
Of course, the 1st function uses strlen() internally, the 2nd one is thus faster.
Now, if it’s known at compile time, I’d like to avoid calculating string length, as laid out here and here:
// Overload 1
template <size_t N>
inline void pushstring(lua_State* L, const char (&str) [N])
{
lua_pushlstring(L, str, N-1);
}
As nice as this function works when called with a string literal: pushstring(L, "test"); of course it doesn’t compile when called with a const char*, for example in a longer function which is in a .cpp file:
// this is in a .cpp file
void long_function(lua_State* L, const char* str)
{
// do lots of stuff
pushstring(L, str); // compile error
// do more stuff
}
Now if I add
// Overload 2
inline void pushstring(lua_State* L, const char* str)
{
lua_pushstring(L, str);
}
it is for some reason (C++ overload resolution is tricky) preferred over Overload 1, which is thus never called.
Is there a clever way to fix that?
To elaborate further on your template version:
See a test run here:
Wrong parameter -> linker error: http://ideone.com/vZbj6
Rigt parameter -> runs great 🙂 : http://ideone.com/iJBAo