Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Template specialization to provide extra member function?

Tags:

c++

templates

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

like image 483
Chikei Avatar asked Nov 09 '09 03:11

Chikei


People also ask

What is explicit template specialization?

Explicit (full) specializationAllows customizing the template code for a given set of template arguments.

When we specialize a function template it is called?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

Can a member function be a template?

Member functions can be function templates in several contexts. All functions of class templates are generic but are not referred to as member templates or member function templates. If these member functions take their own template arguments, they are considered to be member function templates.

What is the specialty of a template function give example?

Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type.


1 Answers

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); }
like image 112
Georg Fritzsche Avatar answered Oct 05 '22 23:10

Georg Fritzsche