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
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;
}
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); }
i think you should understand the following two points :
if the you want to specilize the class primary template, you must put the 'template<>' before the specilized edition declaration.but as for the member function, you needn't put the 'template<...>' before the member function definition(because the type info of the specilized template class has been set by you).
i don't think the primary template class has ant thing to do with the specilized edition.