Alex Semenchenko
Alex Semenchenko

Reputation: 77

Calling object of template class with different template arguments

I'm trying to implement a hash table that can be called in different ways whether hash function and equal operator for some specific type should be defined, like this:

struct FancyType{
//some data here
}

struct SomeHashStruct{
//operator() overload
}

struct SomeEqualStruct(){
//operator() overload
}

HashTable<string, FancyType, SomeHashStruct, SomeEqualStruct> table;

or just define key and value types:

HashTable<string, string> table;

So, I wrote this:

template<typename K, typename V,
typename HashFunction, typename EqualOperator>
class HashTable {
public:
    template<typename K, typename V>
    HashTable() {
    //some fields definition
    }

    template<typename K, typename V,
        typename HashFunction, typename EqualOperator>
    HashTable() {
    //some fields definition
    }
};

The problem is that the first constructor doesn't pass compilation. How can I rewrite this? Are there any C++ features that I missed, or the only way I may only call different constructors of various arguments in order to do it?

Upvotes: 0

Views: 153

Answers (1)

user4581301
user4581301

Reputation: 33962

Two problems and both solved by the same solution.

Problem 1: Shadowing template parameters. the class establishes K and then K is reused by the constructors. Only way out of this is not to do it. You could use other names, but when you have two names for the same thing, confusion is the most common result, and you'll see that separately templating the functions is not necessary.

Problem 2: Template parameters do not take part in overload resolution except through parameters that have their type decided by a template parameter. Since neither constructor have any parameters, they have the same signature and cannot be differentiated.

Solution: Use default template arguments.

template<typename K, typename V,
         typename HashFunction=default_hash_func, 
         typename EqualOperator=default_eguals_op>
class HashTable {
public:
    HashTable() {
    //some fields definition
    }
};

where default_hash_func and default_eguals_op are functions defined elsewhere. The class will use the default unless an argument is supplied when the class is called upon.

Upvotes: 1

Related Questions