Can anyone give me an example of a template method used inside a class?

I am obviously doing it wrong because I am getting all sorts of errors here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template<class T>
class Game
{

private:

    //Game-related
    T processEvents(std::string input);

    void display(T action);
};

template<class T>
T Game<T>::processEvents(std::string input)
{
    
       //
}

template<class T>
void Game<T>::display(T action)
{
   //
}
Try to specify the method in its declaration.
Which errors are you receiveng?
In display, you written "Game<T>". Its only "Game". The same or processEvents.
Last edited on
Perhaps you could be more specific than "I am getting all sorts of errors here?"

http://ideone.com/Qt75P3
Okay, there's been a change of plans. Using a template breaks my program. I want to have a class with both regular and template functions... What is the best way to have some functions like :
1
2
3
4
5
6
7
8
9
10
11
<multiple return types> foo ()
{
    //
}

void bar (<multiple argument types>)
{

      //

}


I want to have some regular non-template functions alongside foo() and bar(), in the same class.Is this possible without templates?
Something like this?

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
38
#include <iostream>
#include <string>

class Game
{
public:

    //Game-related
    template <typename U>
    U processEvents(std::string input);

    template <typename U>
    void display(U action);
};

template<typename U>
U Game::processEvents(std::string input)
{
    std::cout << "Game::processEvents(\"" << input << "\")\n";
    return U();
    //
}

template<typename U>
void Game::display(U action)
{
    std::cout << "Game::Display(" << action << ")\n";
}

int main()
{
    Game game;

    int value = game.processEvents<int>("string1");
    std::string val2 = game.processEvents<std::string>("string2");
    game.display(69);
    game.display("another string");
}


http://ideone.com/MW1303
I'll try this out. By the way, is there any problem if i keep the function declarations in the .cpp file instead of moving them to the .hpp?

Ok tested it, seems to work, (didnt even need to move the declarations to the .hpp).


Cheers for taking the time to explain this!
Last edited on
Topic archived. No new replies allowed.