【发布时间】:2014-01-03 12:33:23
【问题描述】:
我的问题是我有一个模板类,我尝试捕获不同类型数据(int、float、long、char 等)的异常。
#include <iostream>
using namespace std;
const int MAX = 3;
template<class Type>
class Stack()
{
class Range{};
class Empty{};
class Input{};
//Code here
//Code here
//If Error:
throw Range();
throw Empty();
throw Input();
}
int main()
{
try
{
Stack<int> s1
Stack<float> s2
Stack<long> s3
Stack<char> s4
}
catch(Stack<int>::Range) { //Code }
catch(Stack<float>::Range) { //Code }
catch(Stack<long>::Range) { //Code }
catch(Stack<char>::Range) { //Code }
catch(Stack<int>::Empty) { //Code }
catch(Stack<float>::Empty) { //Code }
catch(Stack<long>::Empty) { //Code }
catch(Stack<char>::Empty) { //Code }
catch(Stack<int>::Input) { //Code }
catch(Stack<float>::Input) { //Code }
catch(Stack<long>::Input) { //Code }
catch(Stack<char>::Input) { //Code }
return 0;
}
我怎样才能在 3 行中做同样的事情? 我试过了:
template <class Type>
catch(Stack<Type>::Range) { }
Error: Expected 'catch' before '<' token (What's Wrong)
template<class Type>
try { //Code }
catch(Stack<Type>::Range) { }
Error: A template declaration cannot appear at block scope (Definetely Wrong, I Know)
template<class Type>
int main()
{
try
{
//Code
}
catch(Stack<Type>::Range) { }
}
Error: Cannot declare '::main' to be a template (Of course, That's totally wrong.)
我尝试在很多地方声明“类型”,即使我知道这是错误的。如果我不声明“类型”,那也是错误的。那么,有什么办法可以做到吗?
提前致谢
【问题讨论】:
标签: c++ templates exception types