0

I'm new to c++ and am learning how to handle exceptions. I want the program to throw an exception if I try to add two variables of different types. When I compile, I get the mismatch error and the message that + won't work with the two types, but I want it to throw the exception instead.

#include <iostream>
#include <stdexcept>
#include <typeinfo>
using namespace std;

int main() {
    try{
       int var1 = 6;
       string var2 = "7";
       if (typeid(var1).name() == typeid(var2).name()){
          cout << var1 + var2;
       } else {
          throw 99;
       }
    }catch (int e){
       cout << "caught a " << e << endl;
    }
}
4

2 回答 2

0

不要这样做。但如果你真的想要,你可以:

std::string& operator+(std::string& lhs, int rhs)
{
    throw std::runtime_error("That's really stupid.");
    return lhs;
}
于 2013-10-11T15:06:07.373 回答
0

我不确定这是否是您正在寻找的东西,但是对于您在评论中描述的任何东西,您需要继承。您的所有模板类都必须派生自一个共同的基础,在该基础上进行比较:

private:
    virtual void doBinaryFunction( Base const& other ) const = 0;
public:
    void binaryFunction( Base const& other ) const
    {
        if ( typeid( *this ) != typeid( other ) ) {
            throw std::runtime_error( "Type mismatch" );
        }
        doBinaryFunction( other );
    }

在每个派生类中,您static_castBase const&要做Derived const&,然后做任何必须做的事情。

如果要处理混合类型,则需要某种形式的双重调度。

您还提到实现“加法”,其中要添加的类型不同。这里的问题是添加有一个返回类型,该类型取决于所添加的类型。处理此问题的常用方法是确定规范类型(例如双精度)。在这种情况下,最好的解决方案可能是提供某种虚函数,将值作为规范类型返回,与规范类型进行加法并返回。

无论如何,这有点糟糕的设计。首先,当然,您不会“添加”fordchevy期望得到它们速度的总和。那是没有意义的。您可能会添加ford.speed()and chevy.speed()(尽管我认为添加两辆不相关汽车的速度也没有意义),但无论实现如何,该speed函数都必须返回规范类型的速度;如果 fordchevy具有不同的具体类型,您将通过基类中定义的接口进行调用。

于 2013-10-11T15:21:57.383 回答