Search code examples
c++templatesstructbranch

How versatile are c++'s templates?


I want to write a highly optimized code in C++ and there is a templated structure which takes a type variable T. There is one function wow() in that structure that can be optimized to run twice faster if and only if the size of T is a power of 2. Can I use the better version of wow() without doing branching (use if or something) at the beginning of every call to wow()?

I understand (I hope I do) that C++ creates a copy (or better say instantiation) of my structure for every type T I use it with, so can I tell that "struct builder" which version of wow() to use depending on the size of T?


Solution

  • I would use constexpr if and std::has_single_bit:

    #include <bit>
    
    template<class T>
    struct foo {
        void wow() {
            if constexpr (std::has_single_bit(sizeof(T))) {
                // sizeof(T) is a power of two
            } else {
                // not a power of two
            }
        }
    };