Template class member specialization

Joined
Mar 27, 2009
Messages
8
Reaction score
0
Hey

I would like to specialize a class member function differently for T and for complex<T>. I can do this easily for normal functions, but when I try to do it for class member functions I get an error (error: invalid use of incomplete type 'class bar<std::complex<_Tp> >')

Note: I don't want to specialize the entire class, just the one member function.

Code:
Code:
#include<complex>
#include<iostream>
using namespace std;

// This works fine:
template<class T>
void foo(const T&t){cout << "This is the non-complex function"<<endl;}

template<class T>
void foo(const complex<T>&t){cout << "This is the complex function"<<endl;}

// while this throws an error:
template<class T>
class bar{
public:
  void foo();
// ...
// other definitions identical for T and complex<T>
// ...
};

template<class T>
void bar<T>::foo(){cout << "This is the non-complex member-function"<<endl;}

template<class T>
void bar<complex<T> >::foo(){cout << "This is the complex member-function"<<endl;}
// Throws an "
// error: invalid use of incomplete type 'class bar<std::complex<_Tp> >'
// " error at this definition when compiling

int main()
{
  foo((int)0); // outputs "This is the non-complex function"
  foo((complex<float>)0.); // outputs "This is the complex function"
  bar<int> T1;
  bar<complex<float> > T2;
  T1.foo(); // should output "This is the non-complex member-function"
  T2.foo(); // should output "This is the complex member-function"
  return 0;
}

I'm probably just trying to do it wrong. It's easy if I want to specialize the entire class for either "T" or "complex<T>" (but that requires writing all the common definitions twice). And of course I can always have the member-function "foo" just call the function "foo" (but in my actual code that would require the use of "friend", which I dislike)...

Anyway - was hoping to find out what the correct syntax is :)
Thanks for your help :)
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top