Let’s say I have a class which will be used to create either tree or list structure. Let’s call it
template <typename K, typename V>
class Node{
// some data
Node<K,V>* next;
Node() {
next = static_cast<Node<K,V>*>( malloc( sizeof(Node<K,V>) ));
}
};
By doing this I get a following compiler error:
there are no arguments to ‘malloc’ that depend on a template
parameter, so a declaration of ‘malloc’ must be available (if you use
‘-fpermissive’, G++ will accept your code, but allowing the use of an
undeclared name is deprecated)
Is there any way to use malloc in such a way without having to use deprecated code? I want to use malloc instead of new because I’d like to do some more advanced memory management up there.
The compiler error is telling you that it does not have a declaration of what
mallocis. You are missing the include that declares that function.Other than that, the approach is broken. You are writing a generic tree, but because of the use of
mallocyou are limiting the use to POD types (I am assuming thatKandVare stored in theNode). You should usenewinstead that will call the constructor for the type, not just allocate memory.