Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decltype requires instantiated object

I was experimenting a little with the C++11 standard and came up with this problem:

In C++11 you can use auto and decltype to automatically get return type for a function as, for example the begin() and end() functions below:

#include <vector>

template <typename T>
class Container {
private:
    std::vector<T> v;
public:
    auto begin() -> decltype(v.begin()) { return v.begin(); };
    auto end() -> decltype(v.end()) { return v.end(); };
};

My problem here is that I have to declare the private vector<T> v before the public declarations which is against my coding style. I would like to declare all my private members after my public members. You have to declare the vector before the function declaration because the expression in decltype is a call to vector member function begin() and requires an instance of the object.

Is there a way around this?

like image 248
Felix Glas Avatar asked Oct 24 '25 04:10

Felix Glas


1 Answers

You could avoid using decltype at all and just set the return type to std::vector<T>::iterator.

If you want to use auto though you can use std::declval to get a value from just the type like so:

auto begin() -> decltype(std::declval<std::vector<T>>().begin()) { return v.begin(); };
like image 189
David Brown Avatar answered Oct 26 '25 18:10

David Brown