Hello,
I am writing a C++ (using C++11/0x) wrapper for Lua 5.2.
When i saw the following Lua API functions, i thought i had a genius way of exposing them to C++:
int lua_toboolean(int index);
int lua_tointeger(int index);
const char* lua_tostring(int index);
void* lua_touserdata(int index);
By using template function specilization i eventually came up with this (somewhat, this is a simple compilable example which demonstrates the problem):
This way, i figured, the user of the 'to' method could use template parameters to specifiy the type, and the compiler would figure out which Lua API function to call.Code:#include <iostream> #include <string> // Just pretend that these functions are declared and defined by LUA, // and that they do something actually useful. extern "C" { int lua_toboolean(int index) { return 1; } int lua_tointeger(int index) { return 5; } const char* lua_tostring(int index) { return "Some string"; } void* lua_touserdata(int index) { return reinterpret_cast<void*>(&std::cout); } }; class state { public: state() {} ~state() {} template <typename T> T to(int index) { return reinterpret_cast<T>(lua_touserdata(index)); } template <> int to<int>(int index) { return lua_tointeger(index); } template <> bool to<bool>(int index) { return lua_toboolean(index) == 1; } template <> const char* to<const char*>(int index) { return lua_tostring(index); } private: }; int main(int argc, char* argv[]) { state st; std::cout << st.to<int>(6) << std::endl; std::cout << st.to<bool>(4) << std::endl; std::cout << st.to<const char*>(3) << std::endl }
But there was a problem. This wrapper is meant to be cross platform and standard compliant, so it had to compile under GCC 4.6 as well.
Then i found out that the 'to' method implementation was not standard. Imagine my dismay when i found i had accidentally used a Visual C++ (I am using VS2010) extension without my knowledge!
So my question is, is there a standard way to achieve the same kind of function?



1Likes
LinkBack URL
About LinkBacks


