当我尝试投射到类T的模板,当T的类型为float时,我似乎在下面的代码中出现错误。我已经意识到一种int函数可以正常工作,因为以下语法是有效的:模板铸造问题
char* str = "3";
int num = (int)str;
浮点数也是如此。我想知道是否有办法阻止类型不匹配的g ++编译器错误,所以我可以使用RTTI方法typeid()来处理它。
class LuaConfig {
// Rest of code omitted...
// template currently supports both string and int
template <class T> T getC(const char *key) {
lua_pushstring(luaState, key);
lua_gettable(luaState, -2);
if (!lua_isnumber(luaState, -1)) {
// throw error
std::cout << "NOT A NUMBER" << std::endl;
}
T res;
// WHERE THE PROBLEM IS:
if ( typeid(T) == typeid(int)
|| typeid(T) == typeid(float)
) {
std::cout << "AS NUM" << std::endl;
// Floats should fall in here, but never does because of the
// else clause failing at compile time.
res = (T)lua_tonumber(luaState, -1);
} else {
// TODO: Fails on float here, it should fall down the
// first branch (above). This branch should only be for string data.
std::cout << "AS STRING" << std::endl;
res = (T)lua_tostring(luaState, -1); // LINE THAT CAUSES ISSUE.
}
std::cout << "OUT:" << res << std::endl;
lua_pop(luaState, 1);
return res;
}
}
int main(int argc, char* args[]) {
LuaConfig *conf = new LuaConfig();
std::cout << conf->getC<int>("width") << std::endl;
std::cout << conf->getC<float>("width") << std::endl; // This causes the error.
}
误差克++抛出是:
source/Main.cpp:128: error: invalid cast from type ‘char*’ to type ‘float’
考虑解释你在这里要做的事情。请记住,大多数阅读此文的人可能并不知道lua_xxx函数返回的内容。 – sellibitze 2009-10-04 18:26:59
我不认为typeid(int)或typeid(float)是C++中的有效构造。 typeid通常作为类的vtable的一部分实现,int和float不具有vtable。 – jmucchiello 2009-10-04 19:19:09
撇开它为Comeau/G ++/MSVC编译的事实,我没有看到标准中将'typeid'限制为多态类的任何内容。 – GRB 2009-10-04 19:52:59