c++methodssizeofdecltypenon-static

How do I know the actual type and size of the return type of a non-static method in C++?


In C++, we can use sizeof and decltype on non-static data member of a function, but either of them doesn't work on non-static method's return type, e.g. decltype(std::vector<int>::size()), sizeof(std::vector<int>::size()), any reason why this is restricted? or there are some way works i didn't discovered?


Solution

  • The decltype specifier needs to be given a legal expression - something you could use in actual code. So you can create an instance and call the member on that instance like this:

    decltype(std::vector<int>().size())
    

    It is the same for the sizeof operator. It needs to receive a legal expression.