简体   繁体   English

如何在 std::variant 中调用自定义 class 的正确赋值运算符

[英]How to call proper assignment operator of custom class inside std::variant

I have the following class:我有以下 class:

class StackStringHolder
{
public:
    StackStringHolder& operator=(const std::string& str)
    {
        str_ = str;
        return *this;
    }
    StackStringHolder& operator=(std::string&& str)
    {
        str_ = std::move(str);
        return *this;
    }
    const std::string& get() const { return str_; }

private:
    std::string str_;
};

And I want to use it in the std::variant the following way:我想通过以下方式在std::variant中使用它:

int main() {
    std::variant<int, StackStringHolder> var;
    var = 5;
    std::string str = "Hello";
    var = str; // error
    var = std::move(str); // error
}

However compiler (MSVS2022) says:但是编译器(MSVS2022)说:

error C2679: binary '=': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)错误 C2679:二进制“=”:未找到采用“std::string”类型的右侧操作数的运算符(或没有可接受的转换)

Update, I'm sure my pieces of code enough, but as I'm asked for, here is the complete example:更新,我确信我的代码已经足够了,但正如我被要求的那样,这里是完整的例子:

#include <string>
#include <variant>

class StackStringHolder
{
public:
    StackStringHolder& operator=(const std::string& str)
    {
        str_ = str;
        return *this;
    }
    StackStringHolder& operator=(std::string&& str)
    {
        str_ = std::move(str);
        return *this;
    }
    const std::string& get() const { return str_; }

private:
    std::string str_;
};

int main() {
    std::variant<int, StackStringHolder> var;
    var = 5;
    std::string str = "Hello";
    var = str; // error
    var = std::move(str); // error

    return 0;
}

Your var can hold either an int or a StackStringHolder , so you cannot trivially assign it with a std::string .您的var可以保存一个int或一个StackStringHolder ,因此您不能简单地用std::string分配它。

You can however add a converting constructor to your class StackStringHolder which accepts a std::string .但是,您可以向接受std::string的 class StackStringHolder添加一个转换构造函数
Then it can be used to convert str to StackStringHolder and assign it to var .然后它可以用于将str转换为StackStringHolder并将其分配给var

Your converting constructor can look something like:您的转换构造函数可能类似于:

StackStringHolder(std::string const& str)
    : str_(str)
{}

Now you can use:现在您可以使用:

var = str;
var = std::move(str);

variant::operator= will invoke the constructor to construct the alternative type, so you need to provide the corresponding constructor for StackStringHolder variant::operator=会调用构造函数来构造替代类型,所以需要为StackStringHolder提供对应的构造函数

class StackStringHolder
{
public:
    StackStringHolder(const std::string& str) : str_(str) { }
    StackStringHolder(std::string&& str) : str_(std::move(str)) { }
}

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

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