c++ - MS Visual Studio 2017 上的 Variadic 模板编译问题

标签 c++ visual-studio templates variadic-templates

我需要一个模板来找出类从其基继承的类型及其索引的顺序。该代码适用于 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 为空时。

Live demo

关于c++ - MS Visual Studio 2017 上的 Variadic 模板编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53615749/

相关文章:

python - 在 jinja2 括号中四舍五入

c++ - 我可以有一个要实例化的模板列表,而无需事先实例化吗?

c++ - 编译器可以生成自修改代码吗?

c++ - 使用SSE指令的图像最大值

java - IntelliJ 像在 Visual Studio 中一样自动创建私有(private)字段/方法?

c# - Xamarin 安卓项目

c++ - CRTP子类和实例列表

c++ - 为什么不能 map::find 指向 const 的指针?

c++ - C++ 应用程序的 HTTPS 客户端示例

c# - Windows 10 Enterprise Insider Preview 上 vs 2017 的错误文件图标