编写一个Lua包装器,如何使用可以返回多种类型的方法从堆栈返回一个值
Writing a Lua wrapper, how to return a value from the stack using a method that could return multiple types?
有人能给我解释一下为什么下面的代码不能工作,并提供一个建议,我可以做些什么来使它工作。我是开放使用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;
模板是编译时的概念,而不是运行时的概念。二进制文件中没有模板代码。因此,您的geta不能按原样编译:您不能有时返回一个类型,有时返回另一个类型。但是,您可以这样做
// 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
的模板实例化。
相关文章:
- 如何返回一个类的两个对象相加的结果
- 使用std::mt19937从字符串中返回一个随机单词
- PyRun_String返回一个NoneType对象
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 返回一个带有 std::move 的对象并链接函数
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?
- C++:返回一个基于范围 for 循环迭代器,其中包含继承对象
- 函数可以应用于 std::optional,并返回一个可选值吗?
- readAll() 或 readAllStandardOutput() 在执行之前也返回一个空字符串
- Atmel Studio:返回一个包含数组的寄存器
- 返回一个计算了参数的函数
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 返回一个引用C++中另一个类对象的对象的有效方法
- 从类返回一个字符串 — 奇怪的行为
- 有没有一种方法可以从函数中返回一个新对象或对现有对象的引用
- 我正在尝试从 GMocked 类返回一个 rapidjson::值,但我似乎无法让它工作
- 实现一个函数,该函数将字符串作为输入并返回一个新字符串,辅音字母不替换为 "!"
- 错误 C4716"当事方::运算符+":必须返回一个值
- CStringArray::GetAt(int index) 返回一个 const. 为什么?
- 从system()调用G++会返回一个错误