Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the type of a method member of a class without creating an instance?

Assume we have:

template <typename T>
void foo(std::vector<T> &t) {
    auto var = T();
    std::vector<decltype(var.Get())> array;
}

In the above code, an array is created. The type of this array is whatever the return value of Get() is. We find this value by creating a dummy variable of type T and then infering the return type of Get by using decltype.

This works, however it requires the creation of a dummy variable that serves no purpose.

Instead we could do:

template <typename T>
void foo(std::vector<T> &t) {
    auto var = t[0];
    std::vector<decltype(var.Get())> array;
}

Which doesn't create any dummies, but this will potentially crash, given that we have no guarantee that the array contains at least on element.

Is there a way to infer the type of .Get() without creating a dummy?

like image 654
Makogan Avatar asked Dec 23 '22 21:12

Makogan


1 Answers

std::vector<decltype(t[0].Get())>

t[0] will not be invoked as decltype is an unevaluated context.

Alternatives:

std::vector<decltype(T().Get())>
std::vector<decltype(std::declval<T&>().Get())>
like image 128
Vittorio Romeo Avatar answered Feb 15 '23 23:02

Vittorio Romeo