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

C++ if constexpr vs template specialization

Consider these 2 examples

Example 1

template<Type type>
static BaseSomething* createSomething();

template<>
BaseSomething* createSomething<Type::Something1>()
{
     return Something1Creator.create();
}

template<>
BaseSomething* createSomething<Type::Something2>()
{
     return Something2Creator.create();
}

.... // other somethings

Example2

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

template<Type type>
static BaseSomething* createSomething() 
{
    if constexpr(type == Type::Something1)
    {
        return Something1Creator.create();
    }
    else if constexpr(type == Type::Something2)
    {
        return Something2Creator.create();
    }
    // Other somethings
}

I know that these two examples are conceptually the same, but consider these functional is in a SomethingFactory.hpp file, and my main.cpp includes it.

In main.cpp I may create only type Something1 without ever knowing that other Something types exist.

I really do care about size of my executable in the end. What do you think which pattern shall I take for my executable to be at minimal size? Or there is no big deal about these, and we are all doomed anyway?

>Solution :

What do you think which pattern shall I take for my executable to be at minimal size?

In both cases, if you only instantiate createSomething<Type::Something1> you will get one function definition that is effectively one line of code.

I really do care about size of my executable in the end

Then get rid of the static. Template functions are implicitly inline, but static functions will have unique copies for each translation unit.

I know that these two examples are conceptually the same

They are not.

createSomething<void> is a defined function using Example2, and is undefined using Example 1.

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