Thomas Sparber
Thomas Sparber

Reputation: 2917

Specialize member function for stl container

I have a class like this:

class Foo
{

    ...
    template<template<typename...> class container>
    void fillContainer(container<int> &out)
    {
        //add some numbers to the container
    }
    ...

}

I did it this way to be able to handle different stl Containers. Now I want to create a specialization for std::vector to reserve the Memory (I know the amount of numbers to insert). I read this and this post, so I did the following:

class Foo
{
    //Same Thing as above
}

template<>
void Foo::fillContainer(std::vector<int> &out)
{
    //add some numbers to the container
}

Now I get the error: error: no member function 'fillContainer' declared in 'Foo'. I guess the Problem is template<template<typename...> class container>.

Is there a possibility to specialize this function for std::vector?

Upvotes: 0

Views: 181

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

There is no reason to try and specialize it, just add an overload:

class Foo
{
    ...
    template<template<typename...> class container>
    void fillContainer(container<int>& out)
    {
        //add some numbers to the container
    }

    void fillContainer(std::vector<int>& out)
    {
        //add some numbers to the container
    }

    ...
};

(There are a few, obscure cases where it makes a difference, such as if someone wants to take the address of the function template version, but nothing that requires it to be specialized rather than the much simpler approach of overloading.)

Upvotes: 4

Related Questions