0
votes

I want to write a function that returns a preallocated vector. Since it should work for any kind of vector, I am using a template.

My question is whether it is possible to deduce the template parameter of the function call with the template parameter of the left hand side vector ?

template<typename T>
std::vector<T> createVector(size_t initial) {
    std::vector<T> vec;
    vec.reserve(initial);
    return vec;
}

struct Foo {

};

int main() {

    //std::vector<Foo> foos = createVector(4); // this should work
    //auto foos = createVector<Foo>(4); // this should be okay, too
    std::vector<Foo> foos = createVector<Foo>(4); //duplicate Type :(
}
1
"this should be okay, too" - but it is okay. What's the problem?StoryTeller - Unslander Monica

1 Answers

2
votes

Is it possible to deduce the template parameter of the function call with the template parameter of the left hand side vector ?

No, except for conversion operator (for classes):

struct CreateVector
{
    std::size_t m_capacity;

    CreateVector(std::size_t capacity) : m_capacity(capacity) {}

    template <typename T>
    operator std::vector<T>() const
    {
        std::vector<T> vec;
        vec.reserve(m_capacity);
        return vec;
    }
};

and then

struct Foo {};

int main() {
    [[maybe_unused]]std::vector<Foo> foos = CreateVector(4);
}

Demo