1

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?

Hrant Nurijanyan
  • 789
  • 2
  • 9
  • 26

1 Answers1

1

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.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • I did not get this line *createSomething is a defined function using Example2, and is undefined using Example 1.* why is `createSomething is defined in Example2 and not in Example 1? – TheScore Dec 04 '21 at 19:09
  • @TheScore are you familiar with what a "function definition" is? You can point to the location of the definition of `createSomething` in **Example2**, but you can not point to it in **Example 1**, because it is not there. – Drew Dormann Dec 04 '21 at 19:17
  • Got it. Thank you. Your comment lead to a post saying *A template is a “pattern” that the compiler uses to generate a family of classes or functions. In order for the compiler to generate the code, it must see both the template definition (not just declaration) and the specific types/whatever used to “fill in” the template.* Since in Example2 template func with definition it stamps out implement for different types. Did i get it correctly? – TheScore Dec 04 '21 at 19:26
  • @TheScore I believe so. – Drew Dormann Dec 04 '21 at 19:30