【问题标题】:Define overloaded casting operator for two classes with circular dependency between them为两个具有循环依赖关系的类定义重载强制转换运算符
【发布时间】:2014-10-25 16:38:03
【问题描述】:

我有两个班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;

编译器正在发出

错误 C2027:使用未定义类型“整数”

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

任何帮助将不胜感激。

【问题讨论】:

  • 转发声明字符串并在字符串之前实现整数。还有为什么需要对 intTypeImpl 进行模板化?
  • 如果我将 intTypeImpl 放在首位并转发声明字符串并在发生相同错误后放置字符串“错误 C2027:使用未定义类型'字符串'”。还需要模板类,因为我需要 typedef intTypeImpl 和 intTypeImpl 类型
  • 我能想到的唯一解决方法是将代码拆分为 .hpp 和 .cpp 文件,以便您的标头包含类及其成员变量/函数的声明,然后在 cpp文件你实现了这些成员函数。这是我认为打破循环递归的传统方式
  • 设计有问题,我会避免它。如果您遵循此路径,您将遇到太多问题,更喜欢使用命名函数进行转换。例如,假设您有两个 operator== 一个带有两个 String 对象,另一个带有两个 Integer 对象,并且您尝试比较 StringInteger 并且突然编译器会出现一些歧义错误。 ..
  • @Indika:如果我是你,我不会捕捉到 std::invalid_argument 异常 - 如果使用你的代码的人给出了无效的参数,请告诉他!

标签: c++ casting operator-overloading


【解决方案1】:

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

/* 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-tor 而不是强制转换操作重载使编译器高兴:)
猜你喜欢
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 2017-04-27
  • 2017-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
相关资源
最近更新 更多