问题描述
std :: visit的以下用法在gcc 7.2下可正确编译,但在clang 5.0下无法编译。有人知道问题出在哪里吗?
The following uses of std::visit compiles properly under gcc 7.2 but fails to compile under clang 5.0. Does anyone know what the problem is?
#include <variant>
struct S1 {int foo() { return 0; }};
struct S2 {int foo() { return 1; }};
using V = std::variant<S1, S2>;
int bar() {
V v;
return std::visit([](auto& s) { return s.foo(); }, v);
}
第一个错误是:
include/c++/7.2.0/variant:238:46: error: cannot cast 'std::variant<S1, S2>' to its private base class
'std::__detail::__variant::_Variant_storage<true, S1, S2>'
return __get(std::in_place_index<_Np>, std::forward<_Variant>(__v)._M_u);
以下是godbolt的链接显示此错误:
Here is a link to godbolt shows this error: https://godbolt.org/g/5iaKUm
推荐答案
这是已知的,似乎只影响libstdc ++的 std :: variant
(以及其他使用相同组合的构造)。问题与模板的朋友功能有关-请参见线程。
This is known bug 33222 that seems to only affect libstdc++'s std::variant
(and other constructs using the same combination). The problem is related to friend function to templates - see the thread for more detail.
libc ++的变体似乎没有使用libstdc ++所使用的朋友技术,因此,您可能希望暂时将其更改为libc ++。
The variant from libc++ doesn't seem to use the technique of friends that libstdc++ used, so you might want to temporarily change to libc++ in the meantime.
小更新:此问题已在最新的主干中修复。
Small update: This has been fixed in the latest trunk.
这篇关于std :: visit for variant无法在clang 5下编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!