0

This function template is supposed to return the first element of type X from a tuple using the indexing function, but it won't compile.

template<class X, class F, class... R>
constexpr X getByType(tuple<F, R...> t) {
    if (is_same<F,X>::value) {
        return get<0>(t);                //ERROR POSITION
    }
    if (sizeof...(R) == 0) {
        throw 4;
    }
    return get_vector<X>(tail(t));
}

int main() {
    int i = get<int>(make_tuple(4.2,"assaaa",4));
}

The compiler is saying that it can't cast a double to an int. The first element of this tuple is a double. I guess the reason being the if condition is left to be evaluated at runtime. How can I perform the conditional return of the first element of tuple at compile time?

saga
  • 1,933
  • 2
  • 17
  • 44

1 Answers1

0

In case your compiler does not support constexpr-if, you need to factor out some logic into a helper struct.

Example implementation (could certainly be implemented more efficient):

template<class X, class... List>
struct find_first;

template<class X, class... List>
struct find_first<X, X, List...> { static const int value = 0; };

template<class X, class Y, class... List>
struct find_first<X, Y, List...> { static const int value = find_first<X, List...>::value + 1; };

template<class X, class... R>
constexpr X getByType(tuple<R...> t) {
    return get<find_first<X,R...>::value>(t);
}

Wandbox-Demo

chtz
  • 17,329
  • 4
  • 26
  • 56