c++ - 为什么这个 get_index 实现在 VS2017 上失败了?

标签 c++ visual-studio visual-studio-2017 c++17 variant

巴里给了我们 this gorgeous get_index for variants :

template <typename> struct tag { };

template <typename T, typename V>
struct get_index;

template <typename T, typename... Ts> 
struct get_index<T, std::variant<Ts...>>
    : std::integral_constant<size_t, std::variant<tag<Ts>...>(tag<T>()).index()>
{ };

按如下方式使用:

using V = variant<A, B, C>;
constexpr const size_t N = get_index<B, V>::value;  // 1

它在 Clang (OSX) 中运行良好。

但在 Visual Studio 2017 中 I'm getting以下内容:

<source>(10): error C2039: 'index': is not a member of 'std::variant<tag<Ts>...>'
<source>(10): note: see declaration of 'std::variant<tag<Ts>...>'
<source>(11): note: see reference to class template instantiation 'get_index<T,std::variant<_Types...>>' being compiled
Compiler returned: 2

我不明白为什么。有什么想法吗?

(完全公开:在我的项目中,我实际上使用了 mpark::variant,因为我一直在使用 Xcode 9,它没有 std::variant。但是,您可以从上面的 Godbolt MCVE 可以看出,这也会影响 std::variant 的实现。我确信问题要么出在上面的代码中,要么出在编译器中。)

最佳答案

我敢打赌这是一个编译器错误。

我看到如果我写 main()

std::cout << std::variant<tag<int>, tag<float>>{tag<float>{}}.index() << std::endl;

编译器不会提示。

如果我如下编写模板函数也不会提示

template <typename T, typename ... Ts>
void foo ()
 { std::cout << std::variant<tag<Ts>...>(tag<T>{}).index() << std::endl; }

我称它为 main() , 与

foo<int, long, int, long long>();

main() 中声明以下变量也没问题

std::integral_constant<std::size_t, std::variant<tag<int>, tag<float>>(tag<float>{}).index()>  ic;

但是如果我改变 get_index特化如下(使用大括号代替圆括号进行初始化)

template <typename T, typename... Ts> 
struct get_index<T, std::variant<Ts...>>
    : std::integral_constant<std::size_t, std::variant<tag<Ts>...>{tag<T>()}.index()>
 { };

编译器报错但有不同的错误

example.cpp

(12): error C2440: 'initializing': cannot convert from 'initializer list' to 'std::variant...>'

(12): note: The target type has no constructors

(13): note: see reference to class template instantiation 'get_index>' being compiled

Compiler returned: 2

似乎,由于我无法理解的原因,编译器没有看到 std::variant<tag<Ts>...> , 里面 get_index , 作为 std::variant及其所有方法。

关于c++ - 为什么这个 get_index 实现在 VS2017 上失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53651609/

相关文章:

c++ - g++ 找不到 header ,但我确实包含了它们

c++ - dynamic_cast 上下文中的 "capability query"是什么,为什么有用?

c++ - 初始化作为另一个结构成员的结构 - ISO C++

asp.net-mvc-4 - ASP.NET MVC 4 项目在 Visual Studio 2017 RC 中无法识别

linux - Visual Studio 2017 无法创建目录,mkdir 退出代码 : 1

c++ - 无法将空的初始值设定项分配给 unique_ptrs 的 vector

c# - Xamarin.Forms 空白应用程序 (PCL) 在 Android 上编译错误

c - 编译后 Visual Studio 卡住。当我尝试启动应用程序时,资源管理器也是如此

visual-studio - Electron Cookies错误: Failed to get cookie domain

c++ - 在 Visual Studio 解决方案中设置所有项目的运行时库