template problem

What is wrong with this code ??

temp.h
1
2
3
4
5
6
7
8
9
class temp
{
public:
    temp();
    ~temp();
    
    template <class T> void func(T &param);

};


temp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#include "temp.h"

temp::temp()
{

}

temp::~temp()
{

}
template<class T> void temp<T>::func(T &param)
{
    qDebug() << param;

}

my compiler is wining about a ;
syntax error expected ; before <
I don't get it ..
Last edited on
temp isn't a templated class, so temp<T> isn't legal.
ok thx, you mean
 
template <class T> class temp{..}


but in that case all member functions must be templates...
is there another solution?

Last edited on
ok I found this...
http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file

Another solution is to keep the implementation separated,

not so elegant but maybe the only solution?
Last edited on
ok thx, you mean
template <class T> class Temp{..}

No, that's not what I meant, necessarily.

You need to think about what it is that you actually want to template. Do you want each temp object to be templated on a type? Or do you just want to be able to call the func method with arguments of different types? From what you've shown us of your code, you seem to want the latter, which means you only need the method to be templated, not the whole class.

Another solution is to keep the implementation separated,

The important bit you missed out from that quote is:

and explicitly instantiate all the template instances you'll need:

And, yes, that's not very elegant. Plus, it assumes that the library containing the template can "know" all the different types that the template is going to be used with.
Last edited on
Sorry i'm getting very confused, what should my code look like suppose I only want to make func a template? In what file and what about the explicit instantiaton. I get a lot of compiler errors here

I think I need a break here...
Last edited on
ok, I did forget an #include shame on me ...

temp.h
1
2
3
4
5
6
7
8

template <typename T>
class Foo
{
public:
    void doSomething(T param);
    void normalfunction();
};

temp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template <typename T>
void Foo<T>::doSomething(T param)
{
    qDebug() << param;
}
template <typename T>
void Foo<T>::normalfunction()
{
   qDebug() <<"normal function";

}
//initializer list
template class Foo <int>;
template class Foo <QString>;
template class Foo <ClassX>;

btw i'm using the QT libs

This code works,
but breaks down code completion, so I stick to inline declaration.

I think of using an innerclass in a class + referring to it with a pointer.
http://www.w-uh.com/posts/030126-C++_classes.html
Last edited on
Topic archived. No new replies allowed.