3

For example, I have a class template:

template <typename T>
class base {
public:
   void set(T data) { data_=data; }
private:
T data_;
};

And for a certain type I would like to add a function, but also have functions from the template class.

template <>
class base<int>{
public:
   void set(int data) { data_=data; }
   int get(){ return data_;} //function specific to int
private:
    int data_;
}

How to do that without copying all members from the template class?

Kalamkas
  • 31
  • 1
  • 1
    what you describe would be more like inheritance. I'm not even sure you really want template here. – apple apple Jan 18 '18 at 15:11
  • 1
    Possible duplicate of [Extra method in template specialization](https://stackoverflow.com/questions/5143313/extra-method-in-template-specialization). – xskxzr Jan 18 '18 at 15:13

2 Answers2

1

With inheritance:

template <typename T> struct extra {};

template <> struct extra<int> {
public:
    int get() const;
};

template <typename T>
class base : public extra<T> {
    friend class extra<T>;
public:
   void set(T data) { data_=data; }
private:
    T data_ = 0;
};

int extra<int>::get() const{ return static_cast<const base<int>*>(this)->data_;}

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

You can do this by using enable_if from type_traits to enable the get function only when the template parameter is int. One example is shown below.

#include <type_traits>

template <typename T>
class base {
public:
  template <typename X=T,
            std::enable_if_t<   std::is_same<X,typename T>::value
                             && std::is_same<X,int>::value, bool> = false>
  int get() { return data_; }

  void set(T data) { data_=data; }
private:
  T data_;
};
Johan
  • 3,667
  • 6
  • 20
  • 25
  • 1
    Prefer `std::enable_if_t = false` over `typename = std::enable_if_t`, see [default-template-argument-when-using-stdenable-if-as-templ-param](https://stackoverflow.com/questions/38305222/default-template-argument-when-using-stdenable-if-as-templ-param-why-ok-wit). and that also avoids to call `base::get ` (and condition should be enforced to check that X == T to avoid to call `base::get` ). – Jarod42 Jan 18 '18 at 15:27
  • @Jarod42 Thanks! – Johan Jan 18 '18 at 16:31