如何获取对变量值的引用?
How to get a reference to variant’s value?
我有 std::variant
,其中所有 类 都来自相同的基数。我想将变体转换为基础。
return std::visit( []( const Base& b ) { return b; }, v );
这会编译但给出警告 C4172:返回局部变量或临时变量的地址
有没有办法就地访问 std::variant
,而无需制作本地或临时副本?
或者如果不可能,我如何将值转换为 void*
以便我可以使用 static_cast
?
更新:我认为这个例子应该很明显,但事实并非如此,这是完整的重现:
#include <variant>
struct Base {};
struct A : Base {};
struct B : Base {};
const Base& cast( const std::variant<A, B>& v )
{
return std::visit( []( Base const& b ) { return b; }, v );
}
int main()
{
std::variant<A, B> v{ A{} };
const auto& b = cast( v );
}
Lambda 具有 return 类型推导,但它们按值推导 return 类型。就好像它们是 returning auto
的函数,而不是 decltype(auto)
。如果要return引用,需要指定return类型。
因此,[](const Base& b) { return b; }
returns按值复制b
。通过引用显式指定 return 类型以强制其为 return:
const Base& cast( const std::variant<A, B>& v )
{
return std::visit( []( Base const& b ) -> Base const& { return b; }, v );
}
我有 std::variant
,其中所有 类 都来自相同的基数。我想将变体转换为基础。
return std::visit( []( const Base& b ) { return b; }, v );
这会编译但给出警告 C4172:返回局部变量或临时变量的地址
有没有办法就地访问 std::variant
,而无需制作本地或临时副本?
或者如果不可能,我如何将值转换为 void*
以便我可以使用 static_cast
?
更新:我认为这个例子应该很明显,但事实并非如此,这是完整的重现:
#include <variant>
struct Base {};
struct A : Base {};
struct B : Base {};
const Base& cast( const std::variant<A, B>& v )
{
return std::visit( []( Base const& b ) { return b; }, v );
}
int main()
{
std::variant<A, B> v{ A{} };
const auto& b = cast( v );
}
Lambda 具有 return 类型推导,但它们按值推导 return 类型。就好像它们是 returning auto
的函数,而不是 decltype(auto)
。如果要return引用,需要指定return类型。
因此,[](const Base& b) { return b; }
returns按值复制b
。通过引用显式指定 return 类型以强制其为 return:
const Base& cast( const std::variant<A, B>& v )
{
return std::visit( []( Base const& b ) -> Base const& { return b; }, v );
}