tags:

views:

234

answers:

2

Hello, how do I provide extra member function for specialized template in a non-inline way? i.e.

template<typename T>
class sets
{
    void insert(const int& key, const T& val);
};
template<>
class sets<bool>
{
    void insert(const int& key, const bool& val);
    void insert(const int& key){ insert(key, true); };
};

But when I write sets<bool>::insert(const int& key) as

template<>
class sets<bool>
{
    void insert(const int& key, const bool& val);
    void insert(const int& key);
};
template<>
void sets<bool>::insert(const int& key)
{
    insert(key, true);
}

GCC complains:

template-id ‘insert<>’ for ‘void ip_set::insert(const int&)’ does not match any template declaration

+4  A: 

That's because it is not a function of your template so don't use "template<>". It works for me after removing "template<>" as below:

void sets<bool>::insert(const int& key) 
{ 
    insert(key, true); 
}

My system FC9 x86_64.

The entire code:

template<typename T>
class sets
{
public:
    void insert(const int& key, const T& val);
};

template<>
class sets<bool>
{
public:
    void insert(const int& key, const bool& val) {}
    void insert(const int& key);
};

void sets<bool>::insert(const int& key)
{
    insert(key, true);
}

int main(int argc, char **argv)
{
        sets<bool> ip_sets;
        int key = 10;
        ip_sets.insert(key);
        return 0;
}
EffoStaff Effo
+3  A: 

Besides what Effo said, if you want to add additional functionality in specializations you should move common functionality into a base template class. E.g.:

template<typename T>
class Base
{
public:
    void insert(const int& key, const T& val) 
    { map_.insert(std::make_pair(key, val)); }
private:
    std::map<int, T> map_;
};

template<typename T>
class Wrapper : public Base<T> {};

template<>
class Wrapper<bool> : public Base<bool>
{
public:
    using Base<bool>::insert;
    void insert(const int& key);
};

void Wrapper<bool>::insert(const int& key)
{ insert(key, true); }
Georg Fritzsche