Home > Back-end >  How to overload a template function where a parameter could be a vector of any kind
How to overload a template function where a parameter could be a vector of any kind

Time:03-04

I have a class test which has a vector that contains a bunch of strings. I want to be able to either return the very first value in the vector as any type or an entire vector of any type. (So I could return the first value as an int or the entire data vector as a vector of ints)

What I have right now does not work and I am looking for help overloading the functions:


class test
{
public:
    std::string name;
    std::vector<std::string> data;


    test(const std::string& n) : name(n) {}
    

    void add_data(const std::string& s)
    {
        data.push_back(s);
    }
    
    // return first element of data
    template<typename T>
    T get()
    {
        return convert<T>(data[0]);  //converts data[0] to appropriate type
    }

    //return a vector of any type 
    template<typename T>
    std::vector<T> get<std::vector<T>>()
    {
        std::vector<T> ret_vector;
        for (std::string s : data)
        {
            ret_vector.push_back(convert<T>(s));
        }

        return ret_vector;
    }
};


int main(int argc, char* argv[])
{
    test a("first");
    test b("second");

    a.add_data("2");
    
    b.add_data("bob");
    b.add_data("john");

    a.get<std::string>(); 
    a.get<int>();
    b.get<std::vector<std::string>>();
}

I just am not sure how to properly overload the second get() function. I also think I am doing partial specialization which I have found out is not allowed. Anyway I can get my desired behavior? Right now I get:

test.cpp:30:23: error: expected initializer before ‘<’ token
   30 |     std::vector<T> get<std::vector<T>>()
      |                       ^

Any help much appreciated.

CodePudding user response:

I found a solution from a related post which I could not find before...

    template <typename T>
    T get()
    {
        return get_helper((T*)0); 
    }

    //return a single value
    template <typename T>
    T get_helper(T*)
    {
        return convert<T>(data[0]);
    }

    //return vector of values 
    template <typename T>
    std::vector<T> get_helper(std::vector<T> *)
    {
        std::vector<T> ret_vector;
        for (const std::string s : data)
            ret_vector.push_back(convert<T>(s));

        return ret_vector;
    }

The related post: ambiguous template overload for template parameter is a container

  • Related