有人可以向我解释为什么以下代码不起作用,并就我可以做些什么来使其起作用提出建议。我愿意使用 Boost,但如果可能的话我宁愿不要。从代码中我想做什么应该是相当明显的。 问题是直到运行时我才知道该方法将返回什么类型?
template <typename T>
T getAs()
{
if(typeid(T) == typeid(std::string))
return lua_tostring(lua, stackPos);
if((typeid(T) == typeid(int)) || (typeid(T) == typeid(long)))
return lua_tointeger(lua, stackPos);
if((typeid(T) == typeid(float)) || (typeid(T) == typeid(double)))
return lua_tonumber(lua, stackPos);
if(typeid(T) == typeid(bool))
return lua_toboolean(lua, stackPos);
}
部分错误信息:
In file included from ./luaStackResult.hpp:32:
./luaStackItem.hpp:53:9: error: no viable conversion from 'lua_Integer' (aka 'long') to 'std::basic_string<char>'
return lua_tointeger(lua, stackPos);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/lua.h:320:28: note: expanded from macro 'lua_tointeger'
#define lua_tointeger(L,i) lua_tointegerx(L,i,NULL)
^~~~~~~~~~~~~~~~~~~~~~~~
test.cpp:20:15: note: in instantiation of function template specialization 'cppLua::luaStackItem::getAs<std::basic_string<char> >' requested here
cout << I.getAs<std::string>() << endl;
最佳答案
模板是一个编译时的概念,而不是运行时的概念。二进制文件中没有模板代码。因此,您的 getAs 无法按原样进行编译:您有时无法返回一种类型,有时无法返回另一种类型。但是,你可以做类似的事情
// define general template:
template <typename T> T getAs();
// define specializations for different returned types:
template <> std::string getAs<std::string>() { return lua_tostring(lua, stackPos); }
template <> int getAs<int>() { return lua_tointeger(lua, stackPos); }
template <> float getAs<float>() { return lua_tonumber(lua, stackPos); }
template <> bool getAs<bool>() { return lua_toboolean(lua, stackPos); }
然后当你做
cout << getAs<std::string>() << endl;
编译器会选择正确的特化。运行时将仅包含已在您的源代码中使用的 getAs
的模板实例化。
关于c++ - 编写一个 Lua 包装器,如何使用可以返回多种类型的方法从堆栈返回一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24253794/