简体   繁体   English

带有重载lambda的std :: variant,替换为MSVC?

[英]std::variant with overloaded lambdas, alternative with MSVC?

The cppreference overloaded "trick" where each variant can be visited through a templated operator() overload doesn't compile with the Visual C++ compiler. cppreference重载“技巧”,其中每个变体可以通过模板化的operator()重载访问,不能使用Visual C ++编译器进行编译。 Code snippet can be found here and executes fine when compiled with clang or gcc. 可以在此处找到代码段并在使用clang或gcc编译时执行正常。

However, this doesn't compile with MSVC ( see on godbolt ): 但是,这不能用MSVC编译( 参见godbolt ):

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

It throws various errors and ultimately fails: 它抛出各种错误并最终失败:

warning C4346: 'Ts::()': dependent name is not a type  
note: prefix with 'typename' to indicate a type  
note: see reference to class template instantiation 'overloaded<Ts...>' being compiled  
error C2143: syntax error: missing ';' before '...'  
error C2059: syntax error: '...'  
error C2238: unexpected token(s) preceding ';'  
error C2988: unrecognizable template declaration/definition  
error C2143: syntax error: missing ')' before '...'  
error C2143: syntax error: missing ';' before '...'  
error C2365: 'Ts': redefinition; previous definition was 'template parameter'  
note: see declaration of 'Ts'  
error C2059: syntax error: ')'  
error C2059: syntax error: '->'  
error C2065: 'Ts': undeclared identifier  
error C3544: 'Ts': parameter pack expects a type template argument  

Is there an alternative? 还有其他选择吗? Am I missing options for the compiler? 我错过了编译器的选项吗?

template<class...Ts>
struct overloaded_t {};

template<class T0>
struct overloaded_t<T0>:T0 {
  using T0::operator();
  overloaded_t(T0 t0):T0(std::move(t0)) {}
};
template<class T0, class T1, class...Ts>
struct overloaded_t<T0, T1, Ts...>:T0, overloaded_t<T1, Ts...> {
  using T0::operator();
  using overloaded_t<T1, Ts...>::operator();
  overloaded_t(T0 t0, T1 t1, Ts... ts):
    T0(std::move(t0)),
    overloaded_t<T1, Ts...>(std::move(t1), std::move(ts)...)
  {}
};

template<class...Ts>
overloaded_t<Ts...> overloaded(Ts...ts){ return {std::move(ts)...}; }

or upgrade to latest compiler. 或升级到最新的编译器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM