简体   繁体   English

如何获得对变量值的引用?

[英]How to get a reference to variant’s value?

I have std::variant where all classes are derived from the same base. 我有std::variant ,其中所有类均源自同一基数。 I want to cast variant to base. 我想将变体转换为基础。

return std::visit( []( const Base& b ) { return b; }, v );

This compiles but gives warning C4172: returning address of local variable or temporary 这会编译,但会发出警告C4172:局部变量或临时变量的返回地址

Is there a way to visit std::variant in place, without making local or temporary copies? 有没有一种方法可以访问std::variant ,而不进行本地或临时副本?

Or if it's impossible, how can I cast the value to void* so I can use static_cast ? 或者,如果不可能,如何将值static_castvoid*以便可以使用static_cast

Update: I thought the example should be obvious, but it's not, here's the complete repro: 更新:我认为该示例应该很明显,但是事实并非如此,这是完整的副本:

#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 );
}

Lambdas have return type deduction, but they deduce the return type by value. Lambda具有返回类型推导,但是它们通过值推导返回类型。 It's as if they are a function returning auto , not decltype(auto) . 好像它们是一个返回auto而不是decltype(auto)的函数。 If you want to return by reference, you need to specify the return type. 如果要通过引用返回,则需要指定返回类型。

Thus, [](const Base& b) { return b; } 因此, [](const Base& b) { return b; } [](const Base& b) { return b; } returns by value, copying b . [](const Base& b) { return b; }按值返回,复制b Explicitly specify the return type to force it to return by reference: 明确指定返回类型,以强制其通过引用返回:

const Base& cast( const std::variant<A, B>& v )
{
    return std::visit( []( Base const& b ) -> Base const& { return b; }, v );
}

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

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