Note that there are some explanatory texts on larger screens.

plurals
  1. POTemplate casting issue
    text
    copied!<p>I seem to be getting an error in the below code when I attempt to cast to a template of class T, when T is of type float. I have realized already that a type of int functions correctly, because the following is valid syntax: </p> <pre><code>char* str = "3"; int num = (int)str; </code></pre> <p>The same is not true of float. I'm wondering if there is a way to stop the g++ compiler erroring on a type mismatch so I can handle it with the RTTI method typeid().</p> <pre><code>class LuaConfig { // Rest of code omitted... // template currently supports both string and int template &lt;class T&gt; T getC(const char *key) { lua_pushstring(luaState, key); lua_gettable(luaState, -2); if (!lua_isnumber(luaState, -1)) { // throw error std::cout &lt;&lt; "NOT A NUMBER" &lt;&lt; std::endl; } T res; // WHERE THE PROBLEM IS: if ( typeid(T) == typeid(int) || typeid(T) == typeid(float) ) { std::cout &lt;&lt; "AS NUM" &lt;&lt; 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 &lt;&lt; "AS STRING" &lt;&lt; std::endl; res = (T)lua_tostring(luaState, -1); // LINE THAT CAUSES ISSUE. } std::cout &lt;&lt; "OUT:" &lt;&lt; res &lt;&lt; std::endl; lua_pop(luaState, 1); return res; } } int main( int argc, char* args[] ) { LuaConfig *conf = new LuaConfig(); std::cout &lt;&lt; conf-&gt;getC&lt;int&gt;("width") &lt;&lt; std::endl; std::cout &lt;&lt; conf-&gt;getC&lt;float&gt;("width") &lt;&lt; std::endl; // This causes the error. } </code></pre> <p>The error g++ throws is:</p> <pre><code>source/Main.cpp:128: error: invalid cast from type ‘char*’ to type ‘float’ </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload