简体   繁体   中英

specializing template member function to work in a different way for a special template class

I have two classes class A and class B both of them are template classes for a member function in AI want it to act in a special way when the type of A is B and in a normal way for any other types I don't know how to do this ?

template <class B>
class B
{
private:
  T m;
public:
  ...... any member functions
}

template <class T>
class A
{
private:
  T var;
public:
  void doSomething();
};
template <class T>
void A<T>::doSomething(){...........//implementation}
template <class T> 
void A<B<T>>::doSomething(){................//different implementation}

You can specialize A this way:

template <class T>
class A<B<T>> {
   // ...
};

This is an instance of partial template specialization .

If you refuse to specialize the entire class, you can defer the work from A<T>::doSomething() to a function doSomethingForA<T>(A &) that would be partially specialized, and that would possibly be friend of A<T> .

Hope this solves your problem:

#include <iostream>

template <typename T>
struct B {};

template <typename T> struct A;

template <typename T>
void doSomething(T&) { std::cout << "General\n"; }
template <typename T>
void doSomething(A<B<T>>&) { std::cout << "Special\n"; }

template <typename T>
struct A {
  void doSomething() {
    ::doSomething(*this);
  }  
};

int main()
{
    A<int> general;
    A<B<int>> special;
    general.doSomething();
    special.doSomething();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM