C++ Template recursive to check type in std::tuple
Asked Answered
A

1

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

Arabinose answered 7/9, 2017 at 8:36 Comment(0)
L
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

Leinster answered 7/9, 2017 at 8:39 Comment(2)
got it, I misunderstand compile time ifZabaglione
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?Leath

© 2022 - 2024 — McMap. All rights reserved.