我需要一个模板来找出类从其基继承的类型及其索引的顺序。该代码适用于 clang 和 gcc,但在目标环境 Visual Studio 中,我收到内部编译器错误“ fatal error C1001:编译器中发生内部错误。”。我正在寻找一些解决方法或者可能是我的代码中的错误。是的,我已经尝试过谷歌。
提前致谢。
#include <type_traits>
#include <iostream>
struct BaseA
{
};
struct BaseB
{
};
struct BaseC
{
};
template <class... Types>
class type_list {};
template<typename Type, typename TypeList>
struct get_idx_for_type;
template<typename Type, template<typename...> typename TypeList, typename ...Types>
struct get_idx_for_type<Type, TypeList<Types...>>
{
template<int I, typename T, typename ...Rest>
struct find_type;
template<int I, typename T, typename U, typename ...Rest>
struct find_type< I, T, U, Rest... >
{
// problematic line for compiler, problem is somewhere in find_type recursion
static constexpr int value = std::is_same<T, U>::value ? I : find_type<I + 1, T, Rest...>::value;
};
template<int I, typename T, typename U>
struct find_type< I, T, U >
{
static constexpr int value = std::is_same<T, U>::value ? I : -1;
};
static constexpr int value = find_type<0, Type, Types...>::value;
};
template<typename ...Bases>
struct Foo : public Bases...
{
using base_types_list = type_list<Bases...>;
};
int main()
{
using T = Foo<BaseA, BaseB, BaseC>;
Foo<BaseA, BaseB, BaseC> q;
int a = get_idx_for_type<BaseA, T::base_types_list>::value;
std::cout << a << std::endl;
return 0;
}
最佳答案
内部编译器错误始终是编译器中的错误,无论是否存在 你的代码有什么问题吗?要解决这个问题,您可以替换:
template<int I, typename T, typename U, typename ...Rest>
struct find_type< I, T, U, Rest... >
{
// problematic line for compiler, problem is somewhere in find_type recursion
static constexpr int value = std::is_same<T, U>::value ? I : find_type<I + 1, T, Rest...>::value;
};
与:
template<int I, typename T, typename U, typename V, typename ...Rest>
struct find_type< I, T, U, V, Rest... >
{
static constexpr int value = std::is_same<T, U>::value ? I : find_type<I + 1, T, V, Rest...>::value;
};
协助 VC++ 消除歧义:
template<int I, typename T, typename U>
struct find_type< I, T, U >
{
static constexpr int value = std::is_same<T, U>::value ? I : -1;
};
当 ...Rest
为空时。
关于c++ - MS Visual Studio 2017 上的 Variadic 模板编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53615749/