Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I have to define the same members when I do total specialization of a class template in C++?

I'm very surprised to find that the following compiles:

#include <iostream>

using namespace std;

template<typename T>
class SomeCls {
public:
  void UseT(T t) {
    cout << "UseT" << endl;
  }
};

template<>
class SomeCls<int> {
  // No UseT? WTF?!??!?!
};

int main(int argc, char * argv[]) {
  SomeCls<double> d;
  SomeCls<int> i;

  d.UseT(3.14);
  // Uncommenting the next line makes this program uncompilable.
  // i.UseT(100);

  return 0;
}

Why is this allowed? It just seems wrong that class SomeCls<int> doesn't need to have a void UseT(T t) method. I'm sure I'm missing the point of specialization here (I'm not a C++ expert). Can someone please enlighten me?

like image 852
allyourcode Avatar asked Jun 14 '11 07:06

allyourcode


People also ask

Why do we need template specialization?

It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming.

What is meant by template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

What is template specialisation in c++?

Template Specialization (C++)A template has multiple types and only some of them need to be specialized. The result is a template parameterized on the remaining types. A template has only one type, but a specialization is needed for pointer, reference, pointer to member, or function pointer types.


1 Answers

Because SomeCls<double> is a completely different type than SomeCls<int> or any other SomeCls<T>. They are not related in any way, so they can have whatever members they want. Just be sure not to call i.UseT(), this is where the compiler would start to complain, of course.

like image 85
Christian Rau Avatar answered Nov 15 '22 06:11

Christian Rau