templated methods within templated classes

supposed i have a templated class

1
2
template<typename T>
class myClass;


Is it possible to
a) have a templated method within the class, like below:

1
2
3
4
5
6
template<typename T>
class myClass
{
    template<typename U>
    void myMethod(U input);
};


b) if it is possible, what is the correct syntax for the definition of this function?
c) if it is possible to do so, is it possible to specialize this method?

I have google searched a bit, however with no luck. Any advice would be appreciated.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

template <typename T>
struct A
{
	template <typename U>
	void operator ()( U u ) const;
};

template <typename T>
template <typename U>
void A<T>::operator ()( U u ) const
{
	std::cout << u << std::endl;
}

int main()
{
	A<int>()( 10 );

	return 0;
}
Thanks. That being said, is it possible to specialize the function template which in this case is operator()?

Additionally, I am thinking I should just overload the templated method instead of specializing it. How would the two differ, and is there a rule of thumb to use one or the other?
Last edited on
There is a nice summary on when to use one or the other at Sutter's Mill: http://www.gotw.ca/publications/mill17.htm
You can't specialize method templates but you can do this which give the same result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
template <typename T>
struct S
{
  template <typename V>
  struct S2
  {
    void operator()(S& s, V i)
    {
       /* general code */
    }
  };

  template <>
  struct S2<T>
  {
    void operator()(S& s, T i)
    {
       /* specialized code for V = T */
    }
  };

  template <typename V>
  friend struct S2; // use this if you want to access private members of S in S2

  template <typename V>
  void operator()(V i)
  {
    S2<V>()(*this, i);
  }
};


The friend declaration make struct S2 behave exactly as if it is a method of S since it can access S members.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

template <typename T>
struct A
{
	template <typename U>
	void operator ()( U u ) const;
};

template <typename T>
template <typename U>
void A<T>::operator ()( U u ) const
{
	std::cout << "Inside operator ()<U>() u = " << u << std::endl;
}

template <>
template <>
void A<int>::operator ()( int u ) const
{
	std::cout << "Inside operator ()<int>() u = " << u << std::endl;
}

int main()
{
	task8::A<int>()( 10 );
	task8::A<int>()( 10.0 );

	return 0;
}
Topic archived. No new replies allowed.