Kar*_*rol 4 c++ templates exception
我在为一个嵌套在模板中的类的异常编写catch子句时遇到问题.更具体地说,我对模板和异常有以下定义:
/** Generic stack implementation.
Accepts std::list, std::deque and std::vector
as inner container. */
template <
typename T,
template <
typename Element,
typename = std::allocator<Element>
> class Container = std::deque
>
class stack {
public:
class StackEmptyException { };
...
/** Returns value from the top of the stack.
Throws StackEmptyException when the stack is empty. */
T top() const;
...
}
Run Code Online (Sandbox Code Playgroud)
我有一个以下模板方法,我希望异常捕获:
template <typename Stack>
void testTopThrowsStackEmptyExceptionOnEmptyStack() {
Stack stack;
std::cout << "Testing top throws StackEmptyException on empty stack...";
try {
stack.top();
} catch (Stack::StackEmptyException) {
// as expected.
}
std::cout << "success." << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
当我编译它(-Wall,-pedantic)时,我收到以下错误:
In function ‘void testTopThrowsStackEmptyExceptionOnEmptyStack()’:
error: expected type-specifier
error: expected unqualified-id before ‘)’ token
=== Build finished: 2 errors, 0 warnings ===
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助!
有趣的是,如果堆栈实现不是模板,那么编译器会按原样接受代码.
PS.我也尝试重新定义模板方法类型,但我无法使其工作.
用途typename:
template <typename Stack>
void testTopThrowsStackEmptyExceptionOnEmptyStack() {
Stack stack;
std::cout << "Testing top throws StackEmptyException on empty stack...";
try {
stack.top();
} catch (typename Stack::StackEmptyException) {
// as expected.
}
std::cout << "success." << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
编译器的解析器否则假定它Stack::StackEmptyException不是一个类型并且错误地代码(它不能知道它是一个类型,因为在那时它不知道什么类型Stack,所以可能StackEmptyException同样可能是一个静态数据成员) .您通常也应该通过引用而不是值来捕获.