捕获嵌套模板异常[C ++]

时间:2010-03-14 16:39:22

标签: c++ exception templates

我在为嵌套在模板中的类的异常编写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;
   ...
}

我有一个以下模板方法,我想要捕获异常:

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;
}

当我编译它时(-Wall,-pedantic)我收到以下错误:

In function ‘void testTopThrowsStackEmptyExceptionOnEmptyStack()’:
error: expected type-specifier
error: expected unqualified-id before ‘)’ token
=== Build finished: 2 errors, 0 warnings ===

提前感谢您的帮助!

有趣的是,如果堆栈实现不是模板,那么编译器会按原样接受代码。

PS。我也尝试重新定义模板方法类型,但我无法使其工作。

1 个答案:

答案 0 :(得分:9)

使用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;
}

编译器的解析器否则假定Stack::StackEmptyException不是类型并且错误地代码(它不能知道它是一种类型,因为此时它不知道类型Stack是什么类型,因此可能StackEmptyException同样可能是静态数据成员。您通常也应该通过引用而不是值来捕获。