template specialization for members in classes

Hello,

I already searched about this topic (http://www.parashift.com/c++-faq-lite/templates.html#faq-35.7), but I only found out how to do it for functions without classes or whole classes.
But I want to use it in a class for only some of the functions.
My search resulted in doing it this way:

main.cpp:
1
2
3
4
5
6
...
myclass MyObject;
MyObject.Set<int>(3);
MyObject.Set<string>("hi");
int lint = MyObject.Get<int>;
..


class.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
class myclass
{
...
template <class T>
void Set(T somevar); // for int, long, ...
// template <> ?
void Set<string>(string somestring); // specialisation: string
..
};

template <class T> void myclass::Set(T somevar) { ... }
//template <> ?
void myclass::Set<string>(string somevar) { ... }
...


But it says
Error: template-id ‘Get<std::string>’ in declaration of primary template

How could I fix it?

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
31
32
33
34
35
36
37
#include <iostream>
#include <string>
using namespace std;

class myclass
{
public:
    //only template declaration here
    template <class T>
    void Set(T somevar);
};

//template definition
template <class T>
void myclass::Set(T somevar)
{
    cout << "template" << endl;
}

//template specialization
template <>
void myclass::Set<string>(string somevar)
{
    cout << "specialization" << endl;
}

int main()
{
    myclass asdf;

    asdf.Set(4);
    asdf.Set(string("asdf"));

    cout << "\nhit enter to quit...";
    cin.get();
    return 0;
}
Ah, was very close to the solution.

Thanks for you help, I will test it!

EDIT: I tested it and it works. Thanks again.
Last edited on
Topic archived. No new replies allowed.