C++ Template recursive to check type in std::tuple

2019-07-26 06:48发布

#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

1条回答
Ridiculous、
2楼-- · 2019-07-26 07:19

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

查看更多
登录 后发表回答