简体   繁体   中英

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> {
  ...
};

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM