Recently my class started to dig deeper into working with generics and templates for Java. Since I'm still learning C++, I thought it would be a nice learning experience to translate the Java file.
But for some reason whenever I compile the C++ program, it gives me this error:
1 2 3 4 5 6 7 8 9
gabriel@desktop:/media/gabriel/main/repositories/CPP Sandbox/nodes$ g++ main.cpp node.cpp -o main
/usr/bin/ld: /tmp/ccqvlp1s.o: in function `main':
main.cpp:(.text+0x33): undefined reference to `Node<int>::Node(int)'
/usr/bin/ld: main.cpp:(.text+0x43): undefined reference to `Node<Node<int>*>::Node(Node<int>*)'
/usr/bin/ld: main.cpp:(.text+0x63): undefined reference to `Node<char const*>::Node(char const*)'
/usr/bin/ld: main.cpp:(.text+0x73): undefined reference to `Node<Node<charconst*>*>::Node(Node<charconst*>*)'
/usr/bin/ld: main.cpp:(.text+0x98): undefined reference to `Node<double>::Node(double)'
/usr/bin/ld: main.cpp:(.text+0xa8): undefined reference to `Node<Node<double>*>::Node(Node<double>*)'
collect2: error: ld returned 1 exit status
I'm not too sure on why it's giving me an undefined reference, but if someone could point me to the right direction that would be great.
node.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#pragma once
#include <iostream>
template <typename T>
class Node {
private:
T data;
Node *next_node;
public:
Node(T data);
T get_data();
void set_next_node(Node next);
Node get_next_node();
};
You're not using generics.
Generics are a different concept in other HLLs...
C++ has templates. The defining characteristic of templates is that a version of the template is not generated by the compiler for any type unless it is either a) explicitly specialized or b) used with a type argument that requires a version of that template for the type.
This is why you'll only ever see compiler errors when you use the template object/function/struct, but not when you define them.
To answer your question -- kbw's answer is it. That would result in an explicitly specialized template though.