Node templates with multiple types
Say I have this block of code
1 2 3 4 5 6 7 8 9 10
|
template <class type>
class Node{
private:
type item;
type thing;
Node<type> *next;
public:
type GetNext();
type SetNext(Node<type> new_next);
};
|
If I wanted to use this template with multiple types like this
1 2 3 4 5 6 7 8
|
template <class type1, class type2>
class Node{
public:
type1 item;
type2 thing;
...
};
|
What would I have to type for the mutator and accessor functions?
Or is this not even possible at all?
What would I have to type for the mutator and accessor functions? |
What do you mean by this?
I would suggest to put these different types in a struct or class. The class
Node
shouldn't care for the data type.
Do you mean function like 'getters' and 'setters'? 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
|
#include <iostream>
#include <limits>
#include <string>
template<typename A, typename B> class MyClass {
private:
A item;
B thing;
public:
A getItem() const { return item; }
void setItem(const A& value) { item = value; }
B getThing() const { return thing; }
void setThing(const B& value) { thing = value; }
};
void waitForEnter();
int main()
{
MyClass<double, std::string> mc;
mc.setItem(13.0);
mc.setThing("John Doe");
std::cout << "mc.item:" << mc.getItem()
<< "; mc.getThing: " << mc.getThing() << '\n';
waitForEnter();
return 0;
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
|
Output:
mc.item:13; mc.getThing: John Doe
Press ENTER to continue... |
Topic archived. No new replies allowed.