shayan
shayan

Reputation: 361

overloading a member function of a template class

I have a template class as Tree that insert a value to template class NodeTree . Tree is friend of NodeTree . my function to insert a value to NodeTree is :

template<typename NODETYPE>
void Tree<NODETYPE>::insertNode(const NODETYPE &value)
{
    insertNodeHelper(&rootPtr, value);
}

insertNodeHelper is utility function . i want my insertNodeHelper act different for const string * . first thing came to my mind was overloading it . declaration in the class :

template<typename NODETYPE>
class Tree
{
public:
    Tree();
    void insertNode(const NODETYPE &);
private:
    TreeNode<NODETYPE>*rootPtr;

    void insertNodeHelper(TreeNode<NODETYPE> **, const NODETYPE &);
    void insertNodeHelper(TreeNode<NODETYPE> **, const char *);
};

define :

 template<class NODETYPE>
    void Tree<NODETYPE>::insertNodeHelper(TreeNode<NODETYPE>**ptr, 
        const char *value)
    {
        if (*ptr == 0)
            *ptr = new TreeNode<const char *>(value);
        else
        {
            if (strcmp(value, (*ptr)->data) < 0)
                insertNodeHelper(&((*ptr)->leftPtr), value);
            else if (strcmp(value, (*ptr)->data) >= 0)
                insertNodeHelper(&((*ptr)->rightPtr), value);
        }
    }

template<typename NODETYPE>
void Tree<NODETYPE>::insertNodeHelper(
    TreeNode<NODETYPE>**ptr, const NODETYPE &value)
{
    if (*ptr == 0)
        *ptr = new TreeNode<NODETYPE>(value);
    else
    {
        if (value < (*ptr)->data)
            insertNodeHelper(&((*ptr)->leftPtr), value);
        else if (value >= (*ptr)->data)
            insertNodeHelper(&((*ptr)->rightPtr), value);
    }
}

but i get this error :

1>c:\users\shayan\documents\visual studio 2013\projects\fig21.20\fig21.20\tree.h(54): error C2244: 'Tree<NODETYPE>::insertNodeHelper' : unable to match function definition to an existing declaration

I know that when you have a template function , and an overloaded ordinary one , when compiler is looking for a proper function , it will choose the ordinary for the specific type. but here it does not do that . how to implement a successful overloading ?

Upvotes: 0

Views: 1125

Answers (1)

shayan
shayan

Reputation: 361

I realized my mistake . a function inside a template class that uses classes template parameter is not a template function ! consider this :

template<typename TYPE>
class foo
{
void f1(U);
void f1(char);
}

if you think f1(char) is used for char values you are wrong! when you declare foo<char> compiler generate a code as this :

class foo
{
void f1(char);
void f1(char);
}

there is a simple way to overload f1. like this :

template<typename TYPE>
class foo
{
template<typename I>
void f1(I);

void f1(char);
}

so in this case there is no duplicate function , also template f1 create a proper function , but compiler call ordinary functions before template ones .

Upvotes: 1

Related Questions