开发者

Comparison : C++ template specialization approaches

开发者 https://www.devze.com 2023-02-05 06:42 出处:网络
Which is more correct? And Why. On work I recently run in a discussion how to do a specific开发者_如何学Python template specialization.

Which is more correct? And Why.

On work I recently run in a discussion how to do a specific开发者_如何学Python 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消