c++ - 为两个类之间具有循环依赖关系定义重载转换运算符

标签 c++ casting operator-overloading

我有两个类StringInteger
我希望 String 能够转换为 IntegerIntegerString
我使用运算符重载实现它的方式如下(请注意,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;

编译器正在发出

error C2027: use of undefined type 'Integer'

所以前向声明没有用。
我应该如何实现这个?

任何帮助将不胜感激。

最佳答案

在类外部重载的强制转换运算符:

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

intTypeImpl 中类型转换 c-tor:

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

关于c++ - 为两个类之间具有循环依赖关系定义重载转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564718/

相关文章:

c++ - 我怎么知道哪些库被动态链接到静态库中?

C++ - 将类转换为其他类型

sql - 在 MySQL 中类型转换

c++ - 重载一元运算符 &

c++ - 如何在不违反C++中的DRY原则的情况下实现可移动重载?

c++ - 在 C++ 中为 C 样式对象创建透明包装类

c++ - 在 std::vector 中存储 BSONObj 对象会因大文档而崩溃

c++ - 描述这个元程序的内存消耗

c++ - 如果 lambda 在运行时被移动/破坏会发生什么?

c++ - 将 QByteArray 转换为 `long` 输出相同输入的不同结果