ConfusedSushi
ConfusedSushi

Reputation: 894

Comparison : C++ template specialization approaches

Which is more correct? And Why.

On work I recently run in a discussion how to do a specific template specialization.

This way:

template <typename T, bool someBoolVar = is_polymorphic<T>::value>
struct SomeTemplate { // with empty definition
};

template <typename T>
struct SomeTemplate<T, true> {
  ...
};

template <typename T>
struct SomeTemplate<T, false> {
  ...
};

or this way:

template <typename T, bool someBoolVar = is_polymorphic<T>::value>
struct SomeTemplate; // without empty definition           -- difference here

template <typename T>
struct SomeTemplate<T, true> {
  ...
};

template <typename T>
struct SomeTemplate<T, false> {
  ...
};

Upvotes: 0

Views: 678

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

Neither. Because both will not compile! Wrong syntax for partial specialization!

This is how partial specialization is done:

//correct syntax
template <typename T>
struct SomeTemplate<T,false> {
  ...
};

Not this:

//wrong syntax
template <typename T, false>
struct SomeTemplate {
  ...
};

Now answer to your question assuming you'll fix the syntax!

In my opinion, the second approach is rational, because bool can have ONLY two values, so three versions of SomeTemplate class template doesn't make sense at all, which you're doing in the first approach.

Upvotes: 2

Gene Bushuyev
Gene Bushuyev

Reputation: 5538

Both examples have syntax errors. Assuming you fix them, there isn't any difference between the two. Empty implementation, which you provided in the first example can never be used, so no code generated.

Upvotes: 0

Mike DeSimone
Mike DeSimone

Reputation: 42795

The second way will generate a compiler error if you try to use the template in a way that isn't specialized. The first way just gives you an empty class in those cases, which may or may not generate an error later on when you try to use the class.

The kicker here is that there are only two values for bool and you've specialized for both, so it really doesn't matter which way you go. The empty class won't be linked and thus doesn't generate any extra code.

This specific case is like the compile-time-assertion pattern:

template<bool test> struct compiler_assert;
template<> struct compiler_assert<true> {};

// ...

compiler_assert<bool_test_goes_here> assert1;

Which stops the compile if the test evaluates to false.

Upvotes: 0

Related Questions