Why shouldn't I define the same members when I fully specialize in a class template in C ++?

I am very surprised to find that the following compilation:

#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 seems wrong that it class SomeCls<int>does not need a method void UseT(T t). I am sure that I do not have enough specialization here (I am not an expert in C ++). Can someone please enlighten me?

+5
source share
4 answers

Specialization may specialize as you see fit. If you want to omit all methods, add or remove base classes, add or remove data, then this will be fine.

template <class T>
class Foo {};

template <>
class Foo<int> { void extrafunc(); }; //fine

template <>
class Foo<bool> : public ExtraBase {}; // fine

template <>
class Foo<double> { int extradata; }; // fine

, ( ), .

template <class T>
void foo(const T&);

template <>
void foo<int>(int); // not fine, must be const int&

void foo(int); // fine, this is an overload, not a specialisation

template <class T>
void foo(T*); // fine, again this is an overload, not a specialisation
+7

SomeCls<double> - , SomeCls<int> SomeCls<T>. , , . , i.UseT(), , .

+11

int UseT, .

0

"", . , ; , . . . , ?

, , , .

: . , .

int f(int);
double f(double); //no templates needed

.

. , - , -, typedefs, .. . SomeTemplatedObject<double> , SomeTemplatedObject<T> , SomeTemplatedObject double ""? , ? , , ? .

.

template<typename T>
struct Object;

template<>
struct Object<int> { //what interface does this need?
  typedef int type;
};

If you feel compelled to adhere to a certain definition of OOP, then you can always simply not specialize templates without exact correspondence to their original location.

0
source

All Articles