简体   繁体   中英

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 ?

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM