Search code examples
c++c++11referencedecltype

How can I use decltype to get a pointer without a reference?


I have a function:

auto get_values_at_indices(auto* array, Vector<int>* indices)
{
    std::vector<decltype(*array)> ret(indices->size());

    for (int i = 0; i < indices->size(); i ++)
    {
        int index = indices[i];
        ret.push_back(array[index]);
    }

    return ret;
}

I'm calling the function with

MyClass** array = new MyClass[100];
std::vector<MyClass*> subset = get_values_at_indices(array, indices);

But the compiler sees decltype(*array) as MyClass*& (as opposed to MyClass*, which is what I want) - what should I try?

(PS, I tried std::vector<decltype(&(***array))> ret(indices->size()); but no dice ;)


Solution

  • *array is an lvalue expression, then decltype yields T&, i.e. MyClass*&.

    b) if the value category of expression is lvalue, then decltype yields T&;

    You can perform std::remove_reference (or std::decay depending on your intent) on the type, e.g.

    std::vector<std::remove_reference_t<decltype(*array)>> ret(indices->size());
    

    BTW: decltype(&(**array)) should work, you're giving one more *.