2017-09-07 3 views
1
#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; 
} 

std :: tupleで型のインデックスを検索したいのですが、なぜこのコードをmingw64-gccでコンパイルできないのですか?再帰的なテンプレートが深すぎると私に教えてくれるようです。 std :: tupleで型インデックスを見つける正しい方法は何ですか? gccのバージョン7.2.0、-std = C++ 17std :: tupleでタイプをチェックするC++テンプレート再帰

答えて

3

あなたは第二の条件の前に、最終的なreturnelseを必要としてコンパイルする:elseなければ

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>(); } 
} 

find_from<TupleType, T, index+1>は常にインスタンス化されます以前の条件がtrueと評価されたとしても。

Jarod42 @

live example on wandbox

+1

:おかげで、 –

+0

はそれを得たずさんな説明を変更し、私があれば、時間をコンパイル誤解します –

関連する問題