0

I try to implement a template with an explicit template specification. The template and its implementation is shown bellow:

template <typename T>
class MyClass {
private:
    T data;
    size_t size;

public:
    MyClass();
    ~MyClass();

    uint32_t getSize();

    T getData();
    void setData(T value);
};
template <class T>
MyClass<T>::MyClass()
{
    size = sizeof(T);
}
template <>
MyClass<std::string>::MyClass()
{ 
    size = 0;
}

/* and so on */

Now I have an issue when my explicit declaration contains also a class template. Let say, i would create an explicit template specialization of a vector (containing any primitive type like int, char, float,...) and store the element site in the size variable.

template <??>
MyClass<std::vector<?>>::MyClass()
{ 
    size = sizeof(?);
}

How could I do this?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
moudi
  • 478
  • 4
  • 17
  • Off Topic: when possible, use initialization list and avoid initialization inside the body of constructors; so, in your case, `template MyClass::MyClass() : size{sizeof(T)} {}` – max66 Feb 08 '20 at 17:59
  • Oh thanks for that input. Yes it make sens to put them into an initialization list. I found more information about that on: https://stackoverflow.com/questions/9903248/initializing-fields-in-constructor-initializer-list-vs-constructor-body – moudi Feb 10 '20 at 11:22

1 Answers1

2

You should specialize class, not methods:

#include <string>
#include <vector>

template <typename T>
class MyClass {
private:
    T data;
    size_t size;

public:
    MyClass();
    ~MyClass();

    uint32_t getSize();

    T getData();
    void setData(T value);
};

template <class T>
MyClass<T>::MyClass()
{
    size = sizeof(T);
}
template <>
MyClass<std::string>::MyClass()
{ 
    size = 0;
}

template<class T>
class MyClass<std::vector<T>>
{
    MyClass();

    T data;
    size_t size;
};

template<class T>
MyClass<std::vector<T>>::MyClass()
{ 
    size = sizeof(T);
}
273K
  • 29,503
  • 10
  • 41
  • 64
  • Hi S.M. Thanks for the hint. The template creation is quite new for me and I'm still in a learning phase. For me, the new thing from your answer is, that an template class could be defined twice, once with a more specific type (e.g. `std::vector`). I could realize my goal thanks to that. – moudi Feb 10 '20 at 11:18