Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specialize only some members of a template class?

Code:

template<class T>
struct A {
  void f1() {};
  void f2() {};

};

template<>
struct A<int> {
  void f2() {};
};


int main() {
  A<int> data;
  data.f1();
  data.f2();
};

ERROR:

test.cpp: In function 'int main()':
test.cpp:16: error: 'struct A<int>' has no member named 'f1'

Basically, I only want to specialize one function and use the common definition for other functions. (In actual code, I have many functions which I don't want to specialize).

How to do this? Thanks!

like image 737
anon Avatar asked Feb 10 '11 10:02

anon


People also ask

What is the difference between a template and a class?

An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated. Note the distinction between the terms class template and template class: Class template.

What is the specialty of a template function give example?

Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type.

How would you define member function outside the class template?

Member functions of class templates (C++ only) You may define a template member function outside of its class template definition. The overloaded addition operator has been defined outside of class X . The statement a + 'z' is equivalent to a. operator+('z') .

When we specialize a function template it is called?

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.


2 Answers

Would this help:

template<typename T>
struct A
{
  void f1()
  {
    // generic implementation of f1
  }
  void f2()
  {
    // generic implementation of f2
  }
};

template<>
void A<int>::f2()                                                               
{
  // specific  implementation of f2
}
like image 80
Tomek Avatar answered Oct 26 '22 23:10

Tomek


Consider moving common parts to a base class:

template <typename T>
struct ABase
{
    void f1();
};


template <typename T>
struct A : ABase<T>
{
    void f2();
}  


template <>
struct A<int> : ABase<int>
{
    void f2();
};

You can even override f1 in the derived class. If you want to do something more fancy (including being able to call f2 from f1 code in the base class), look at the CRTP.

like image 27
Alexandre C. Avatar answered Oct 27 '22 00:10

Alexandre C.