2
#include <iostream>
#include <tuple>
#include <type_traits>

template<typename TupleType, typename T, std::size_t index = 0> constexpr std::size_t find_from(){
    if constexpr (index == std::tuple_size_v<TupleType>) return index;
    if constexpr (std::is_same_v<std::tuple_element_t<index, TupleType>, T>) return index;
    return find_from<TupleType, T, index+1>();
} 

int main(){
    std::cout << find_from<std::tuple<int,double>, int, 0>()<< std::endl;
}

I want to find the index of a type in a std::tuple, Why this code can't compile in mingw64-gcc? It seem to tell me template recursive is too deep. What's the right way to find a type index in std::tuple? gcc version 7.2.0 ,compile with -std=c++17

0

1 Answer 1

4

You need an else before the second condition and before the final return:

template<typename TupleType, typename T, std::size_t index = 0> 
constexpr std::size_t find_from()
{
    if constexpr (index == std::tuple_size_v<TupleType>) { return index; }
    else if constexpr (std::is_same_v<std::tuple_element_t<index, TupleType>, T>) { return index; } 
    else { return find_from<TupleType, T, index+1>(); }
} 

Without the else, find_from<TupleType, T, index+1> will be always instantiated even if the previous conditions evaluated to true.

live example on wandbox

Sign up to request clarification or add additional context in comments.

2 Comments

got it, I misunderstand compile time if
Is this code you provided in our answer public domain (in other words, there is absolutely no ownership such as copyright, trademark, or patent)? Or which restrictions do apply If I want to reuse your code snippet?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.