3

I am trying to create a template function that is overloaded for pointer and non pointers. I did this and it works.

    template<class D, class V>
    bool Same(D d, V v){ return d == v; }

    template<class D, class V>
    bool Same(D* d, V v) { return *d==v;}

Now I want to extend it such that a templated container is a paramater and there must be one version for the container with pointer and other with the container for non pointers. I am not able to figure it out. I tried this but it won't work.

    template< template<class> class Container, class Data, class Value>
    bool func(Container<Data> &c, Value v)
    {
        return c[0] == v;
    }

    template< template<class> class Container, class Data, class Value>
    bool func(Container<Data*> &c, Value v)
    {
            return *c[0] == v;
    }

The error c2040 says int* differs in level of indirection from int and points to the first function.

How can I get it to work?

Rest of thecode

template<class D>
class Vec
{
    std::vector<D> m_vec;
public:
    void push_back(D d) { m_vec.push_back(d); }
        D operator[](int i) { return m_vec[i]; }
};
void test_template()
{
    Same<int, int>(2,3);
    Info i = {4};
    Same<Info, int>(i, 2);
    Info ii = {2 };
    Info *pi = &ii;
    Same<Info, int>(pi, 2);

    Vec<int> iv;
    iv.push_back(3);
    func<Vec, int, int>(iv, 3);
    Vec<int*> pv;
    pv.push_back(new int(3));
    func<Vec, int*, int>(pv, 3);
}

1 Answer 1

3

For the second call to func, the second template parameter should just be int, not int *. Otherwise, the second func declaratino will look for a Vec<int **> as the first template argument (since it has its own pointer).

func<Vec, int, int>(pv, 3);

EDIT: as DyP mentioned, you can also leave out the template arguments completely, as the compiler should be able to deduce them from the actual function arguments.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.