charmoniumQ
charmoniumQ

Reputation: 5513

Template specialize a method

I have a method which is templated, and I want add a specialization. For a function, I would write

template<> T function<typename T>() { /* ... */ }

How do I do this for a method?

Here is a minimal failing example where I need to specialize recv for <char>.

#include <vector>

class recver_t {
public:

    // recv should work for chars, ints, and lists of those.

    template <typename list_t, typename elem_t>
    list_t recv() {
        list_t list;
        for (int i = 0; i < 10; ++i) {
            list.push_back(recv<elem_t>());
        }
        return list;
    }

    // How to specify this template?
    // It needs to be a template taking 1 typename, but specialized for <char>
    // I need the template spec because I am overloading by return-type.
    char recv() {return '\0';}

    // likewise, but for int
    //int recv() {return 0;}
};

int main() {
    recver_t recver;
    // std::vector<char> result = recver.recv<std::vector, char>();
    // EDIT: should be this
    std::vector<char> result = recver.recv<std::vector<char>, char>();
}

Upvotes: 2

Views: 90

Answers (1)

Robert Andrzejuk
Robert Andrzejuk

Reputation: 5222

If You want to make ONLY specializations, then:

First create the primary definition of the template:

template<typename T>
T recv();

Then only create the specializations:

template<>
char recv<char>() {return '\0';}

// likewise, but for int
template<>
int recv<int>() {return 0;}

If somebody uses the templates which have a missing specialization then the linker will show an error message about missing functions.

Therefore You have to delete, either specific specializations:

template<> 
float recv<float>() = delete;

or all other specializations, but then this definition has to replace the primary definition:

template<typename T> 
T recv() = delete;

Upvotes: 2

Related Questions