Search code examples
c++templatescompile-timespecializationif-constexpr

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

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.