【发布时间】:2021-04-20 11:08:57
【问题描述】:
我正在尝试学习如何使用带有模板参数的自定义 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 的问题吗?
【问题讨论】:
标签: c++ c++11 templates exception