Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template specialization on std::vector<T>

I'm trying to write a template function that will handle any type of argument, including vectors, maps etc, but I'm having trouble.

template<class C>
void foo(C c);

template<>
template<class V>
void foo<std::vector<V> >(std::vector<V> v);

The compiler (g++ 4.9.2-10) will complain about this:

test.cpp:13:43: error: too many template parameter lists in declaration of ‘void foo(std::vector<V>)’
 void foo<std::vector<V> >(std::vector<V> v) {
                                           ^
test.cpp:13:6: error: template-id ‘foo<std::vector<V> >’ for ‘void foo(std::vector<V>)’ does not match any template declaration
 void foo<std::vector<V> >(std::vector<V> v) {
      ^
test.cpp:13:43: note: saw 2 ‘template<>’, need 1 for specializing a member function template
 void foo<std::vector<V> >(std::vector<V> v) {
                                           ^

How can I achieve this? I also want to specialize on std::map<std::string, V>

removing the first template<> line from the specialization still doesn't work (illegal specialization)

like image 439
Bogdan Ionitza Avatar asked Dec 25 '22 04:12

Bogdan Ionitza


2 Answers

You cannot partially specialize a function, you want to create a new overload:

template <class C>
void foo(C c);

template <class V>
void foo(std::vector<V> v); // This is a different overload, not a specialization!

Please note the difference with a partial specialization of foo:

template <class C>
void foo(C c); // 1

template <class V>
void foo<std::vector<V>>(std::vector<V> v); // 2

Here 2 is a partial specialization of 1, which is not allowed in C++ for function.

like image 60
Holt Avatar answered Jan 11 '23 06:01

Holt


You may find it convenient to overload on the basis of the traits of the container.

This allows a little more flexibility in terms of accepting references, const references and r-value references while only writing the function once.

Here is a small example which implements a template foo for anything which has a begin() and an end() method, except for std::strings, which gets its own version of foo via a non-template overload:

#include <vector>
#include <map>
#include <iostream>
#include <iomanip>

// trait type to determine whether something models a range.
template<class T>
struct is_range
{
    template <class Y> static auto has_begin(T*p) -> decltype(p->begin(), void(), std::true_type());
    template <class Y> static auto has_begin(...) -> decltype(std::false_type());

    template <class Y> static auto has_end(T*p) -> decltype(p->end(), void(), std::true_type());
    template <class Y> static auto has_end(...) -> decltype(std::false_type());

    static constexpr bool value = decltype(has_begin<T>(0))::value && decltype(has_end<T>(0))::value;
};


// specialised mini-functor for dealing with corner cases
template<class T>
struct emitter
{
    std::ostream& operator()(std::ostream& os, const T& t) const {
        return os << t;
    }
};

template<class T, class U>
struct emitter<std::pair<T, U>>
{
    std::ostream& operator()(std::ostream& os, const std::pair<T, U>& p) const
    {
        return os << "(" << p.first << ", " << p.second << ")";
    }
};

// a version of foo which works for all known containers, whether temporararies or references
template<class Container,
std::enable_if_t<is_range<std::decay_t<Container>>::value and not std::is_same<std::decay_t<Container>, std::string>::value>* = nullptr
>
void foo(Container&& c)
{
    // do things with c.begin(), c.end()
    bool first = true;
    for (auto& x : c) {
        using emitter_type = emitter<std::decay_t<decltype(x)>>;
        auto emit = emitter_type();
        if (first) {
            first = false;
        } else {
            std::cout << ", ";
        }
        emit(std::cout, x);
    }
    std::cout << std::endl;
}

// overload for std string

void foo(const std::string& s)
{
    std::cout << std::quoted(s) << std::endl;
}

int main()
{
    using namespace std::literals;

    foo(std::map<std::string, std::string> {
        {
            { { "foo" }, { "bar" } },
            { { "aaaa" }, { "bbbbb" } }
        }
    });
    foo(std::vector<std::string> {
        { "foo" },
        { "bar" },
        { "xxxx" },
        { "yyyy" } });

    foo("hello"s);

}

expected output:

(aaaa, bbbbb), (foo, bar)
foo, bar, xxxx, yyyy
"hello"
like image 24
Richard Hodges Avatar answered Jan 11 '23 07:01

Richard Hodges