Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
        }
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading