creating this template function

Apr 21, 2012 at 6:24pm
So I have a template class containing:

1
2
3
4
5
6
7
8
9
10
11
12
// someProgram.h
template <class T>
class myClass
{
public:
   struct someStruct{...}; 
   someStruct * getHead();  // return a pointer to private member 'head'

private:
someStruct * head;
...
}


How would I define my getHead() function in my .cpp file? I've tried this with no luck:
1
2
3
4
template <typename T>
myClass<T>::someStruct *myClass<T>::getHead(){

}


With the above definition I get the error:
"Error 7 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int"

and


Error 6 error C2143: syntax error : missing ';' before '*'
Last edited on Apr 21, 2012 at 6:45pm
Apr 21, 2012 at 7:07pm
In principle you can't, which is called the "Inclusion model", where you have to put your implementations in your header file, which is totally fine!!!

BUT, if you insist on having a separate file, there are 2 ways to do it:

1- declaration model
2- separation model

In the first one, you have to instantiate each type you're gonna use in you're gonna use, which makes things way too bad if you have big projects.

The second one is for pros. It's not easy to use it and could mess stuff up. In this, you add the word "export" before your template class. Please read more details about this here:

http://codeidol.com/cpp/cpp-templates/Using-Templates-in-Practice/The-Separation-Model/

Cheers :)
Last edited on Apr 21, 2012 at 7:09pm
Apr 21, 2012 at 8:00pm
Well the way I have it is I #included my .cpp file at the bottom of my .h file and "exported from build" in visual studio....is that the same concept?
Apr 21, 2012 at 8:10pm
In this, you add the word "export" before your template class.


export is no longer with us in C++11.

#including your .cpp file in the .h file is the same as putting the implementation into your .h file. I don't see any reason not to do it directly, myself.

Apr 21, 2012 at 8:35pm
Alright, so now that I have the .cpp file all in the .h file how does that affect my original problem?
Apr 21, 2012 at 8:47pm
Having trouble getting head?

</perv-troll>

You just define the functions right inside of the class definition, like so:

1
2
3
4
5
6
7
8
template <typename T>
class Bill
{
    std::string getName()
    {
        return "Bill";
    }
};
Apr 21, 2012 at 8:56pm
Try:
1
2
3
4
template <typename T>
typename myClass<T>::someStruct *myClass<T>::getHead()
{
}
Apr 22, 2012 at 9:37pm
thanks
Topic archived. No new replies allowed.