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

前端 未结 3 901
别那么骄傲
别那么骄傲 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 22:49

    To expand on my comment:

    The if runs at runtime, not compile time (the optimizer might remove the branch, but it has to compile in the first place to get that far).

    You can use template specialization instead, which is done at compile time (the compiler instantiates a separate copy of the templated function for each type you give it before compiling it). You can provide a specialization to force a different (special) function body for particular types, which is exactly what you want in this case.

    Here's an example derived from the code in your question (I'm assuming the double-push_back to kvec for non QUAT32s is a typo):

    template
    inline void readKey(T& key, FILE* fh)
    {
        fread(&key, sizeof(T), 1, fh);
    }
    
    template<>
    inline void readKey(QUAT32& key, FILE* fh)
    {
        shortQuat key16;
        fread(&key16, sizeof(shortQuat), 1, fh);
        key.Parse(key16);
    }
    
    // ...
    vector kvec;
    for (ulong kv = 0; kv < ke.count; kv++)
    {
        T key;
        readKey(key, fh);
        kvec.push_back(key);
    }
    

提交回复
热议问题