本文介绍了C ++模板递归检查std :: tuple中的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 ++ 17

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

推荐答案

在第二个条件之前和最后一个return之前,您需要else:

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

在没有else的情况下,即使以前的条件计算为true,也会始终实例化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.

魔盒上的在线示例

这篇关于C ++模板递归检查std :: tuple中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:58