Why does the compiler seem to ignore if statements in templated classes?

前端 未结 3 902
别那么骄傲
别那么骄傲 2021-01-16 22:14

First off, the code

vector kvec;

for (ulong kv = 0; kv < ke.count; kv++)
{
    T key;
    if (typeid(T) != typeid(QUAT32))
    {


        fread         


        
3条回答
  •  悲哀的现实
    2021-01-16 23:06

    Problem: Needed to handle a special case in a templated constructor, that needed to be converted for usefulness. But, as I feared, if statements are ignored on compile.

    Solution:

    Add a second type to the template, and create a type-cast operator in one of the types.

    vector kvec;
    for (ulong kv = 0; kv < ke.count; kv++)
    {
        T2 key;
        fread(&key, sizeof(T2), 1, fh);
        kvec.push_back((T)key);
    }
    

    In most cases, the class would be constructed like so:

    SomeClass c = SomeClass(fh);
    

    obviously, casting between the same type should be pretty straightforward. But in the case of QUAT32...

    SomeClass c = SomeClass(fh);
    

    the solution was to just do this:

    typedef struct SHORT_QUAT
    {
        short x;
        short y;
        short z;
        short w;
        operator const QUAT32(){
            QUAT32 q;
            q.x = float(x < 0 ? x + 32768 : x - 32767) / 32767.0f;
            q.y = float(y < 0 ? y + 32768 : y - 32767) / 32767.0f;
            q.z = float(z < 0 ? z + 32768 : z - 32767) / 32767.0f;
            q.w = float(w < 0 ? w + 32768 : w - 32767) / 32767.0f;
            return q;
        }
    }shortQuat;
    

    and then the data that was stored in shortquat form could be cast to the more useful float format without issue.

    It just seemed like a waste to have to create an entire duplicate just for a special case. I'd like to think it's the lesser of two ugly.

提交回复
热议问题