带有模板参数的自定义C ++异常

医学物理学家

我正在尝试学习如何将自定义C ++异常与模板参数一起使用。这是我尝试无法成功编译的虚拟程序:

#include <string>
#include <iostream>

template <class T>
class MyException : public std::exception {
    public:
        T error;
        MyException(T err) { error = err; };
};


int main(void) {
    try {
        std::string err = "String error";
        throw MyException<std::string>(err);
        return 0;
    }
    catch (MyException e) {
        std::cout << e << std::endl;
        return 1;
    };
}

这是我得到的错误:

<source>: In function 'int main()':
<source>:18:9: error: invalid use of template-name 'MyException' without an argument list
   18 |  catch (MyException e) {
      |         ^~~~~~~~~~~
<source>:18:9: note: class template argument deduction is only available with '-std=c++17' or '-std=gnu++17'
<source>:5:7: note: 'template<class T> class MyException' declared here
    5 | class MyException : public std::exception {
      |       ^~~~~~~~~~~
<source>:19:22: error: 'e' was not declared in this scope
   19 |         std::cout << e << std::endl;
      |                      ^

您能帮我为C ++ 11修复它吗?

马雷克

您找不到任何模板!您只能捕获特定类型,因此只能捕获模板的特定实例。因此,您的代码应如下所示(快速修复):

#include <string>
#include <iostream>

template <class T>
class MyException : public std::exception {
    public:
        T error;
        MyException(T err) { error = err; };
};


int main(void) {
    try {
        std::string err = "String error";
        throw MyException<std::string>(err);
        return 0;
    }
    catch (const MyException<std::string>& e) {
        std::cout << e.what() << std::endl;
        return 1;
    };
}

https://godbolt.org/z/P4czdP

如果您需要某种方式来捕获此模板的所有异常,则需要额外的继承层以为此模板引入通用的唯一父类型:

#include <string>
#include <iostream>


class MyCommonException : public std::exception
{};

template <class T>
class MyException : public MyCommonException {
    public:
        T error;
        MyException(T err) { error = err; };
};


int main(void) {
    try {
        std::string err = "String error";
        throw MyException<std::string>(err);
        return 0;
    }
    catch (const MyCommonException& e) {
        std::cout << e.what() << std::endl;
        return 1;
    };
}

https://godbolt.org/z/xz8r5a

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章