Darien Pardinas
Darien Pardinas

Reputation: 6186

Do C++ compilers optimize template methods based on template arguments?

Are C++ compilers able to optimize a code like this in a way that concrete method implementations ( if (little_endian) => if(true)or if(false)) would only contain the relevant code or do I need to use type_traits and provide two separate implementations in order to ensure that my code will be optimized (i.e. no branch prediction)?

template <typename T, bool little_endian = true> bool readValue(T& value)
{
    if (m_num_bytes_parsed + sizeof(value) <= m_num_bytes_total)
    {
        if (little_endian)
        {
            m_file_stream.read((char *)(&value), sizeof(value));                    
        }
        else
        {
            char bytes[sizeof(T)];
            m_file_stream.read((char *)(&value), sizeof(value));
            std::reverse(bytes, bytes + sizeof(value));
            memcpy(&value, bytes, sizeof(T));
        }
        m_num_bytes_parsed += sizeof(value);
        return true;
    }
    return false;
}

Upvotes: 2

Views: 68

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275270

Yes, every compiler worth its salt will optimize if(true) and if(false) and otherwise collapse simple constant expressions.

There may be some obscure compilers that fail to do this. To be explicit, current versions of gcc, clang, intel and msvc will all do this to my knowledge, and I haven't run into a compiler that does not do this.

Upvotes: 2

Related Questions