Chan Kim
Chan Kim

Reputation: 5919

templated type with no template variable and other templated type using such

I can't exactly understand C++ code lines below.
Why does line 1 use template when T is not appearing in line 1? Does it mean when struct bits are declared with certain template type, (like bits<float>), it just does typdef unsigned char type; inside the struct?

In line 2, does it mean if I declare struct bits<const float>, it also intitlaizes a struct bits<float> using line 1? meaning bits is like bits<float> ?
I would appreciate if someone explains what this code is doing or refer me to a good reference about this topic.

    /// Type traits for floating point bits.
    template<typename T> struct bits { typedef unsigned char type; };  // line 1
    template<typename T> struct bits<const T> : bits<T> {};  // line 2
    template<typename T> struct bits<volatile T> : bits<T> {};  // line 3
    template<typename T> struct bits<const volatile T> : bits<T> {};  // line 4

Upvotes: 1

Views: 113

Answers (1)

Johnathan Gross
Johnathan Gross

Reputation: 678

There is no reason that a template parameter has to be used by the template. The unused parameter can be used to delineate different versions of the templated class/function/variable that have nothing to do with the template parameter itself.

template<int N> bool f();
template<1> bool f(){return true;};
template<0> bool f(){return false;};

In line 2, bits<const T> is inheriting from bits<T>. It isn't initializing an instance of bits<T>, but gaining all the pieces of it as if it were part of itself. All that happens when bits<const T> is initialized is that it will define a type type, like it does for bits<T>.

Upvotes: 2

Related Questions