为两个类定义重载的强制转换运算符,这两个类之间具有循环依赖关系

Define overloaded casting operator for two classes with circular dependency between them

本文关键字:两个 之间 依赖 关系 循环 重载 定义 转换 运算符      更新时间:2023-10-16

我有两个类StringInteger
我希望String能够被转换为Integer并且Integer能够被转换成String
我使用运算符重载实现它的方式如下(注意Integer类是基于模板的)

#include <string>
class Integer; // forward declaration but doesnt fix the compiler error
class String {
public:
    operator Integer() {                                                
        try {                                               
            return std::stoi(s);
        catch(std::invalid_argument ex) {                                           
        }                                               
    }
    std::wstring s;
};
template<class T>
    class intTypeImpl {
    T value;
public:
    typedef T value_type;
    intTypeImpl() :value() {}
    intTypeImpl(T v) :value(v) {}
    operator T() const {return value;}
    operator String() {         
        return std::to_wstring(value);                                      
    }
};
typedef intTypeImpl<int> Integer;

编译器正在发布

错误C2027:使用未定义的类型"Integer"

因此正向声明没有任何用处
我应该如何实现这一点?

如有任何帮助,我们将不胜感激。

在类外重载铸造运算符:

/* after every line of code you posted */
operator Integer(const String& str){
    return std::stoi(str.s);
}

intTypeImpl中的铸件:

#include <type_traits>
/* in intTypeImpl */
intTypeImpl()=default;
intTypeImpl(const intTypeImpl<T>&)=default;
intTypeTmlp(String& str){
    static_assert(
        std::is_same<T, int>,
        "String can be converted only to intTypeImpl<int>"
    );
    value=std::stoi(str.s);
}