Catching a nested template exception [C ++]

I have a problem writing a catch clause for an exception, which is a class nested in a template. To be more specific, I have the following template definition and exceptions:

/** 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; ... } 

I have the following template method that I want to exclude for catch:

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

When I compile it (-Wall, -pedantic), I get the following error:

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

Thanks in advance for your help!

Interestingly, if the stack implementation was not a template, then the compiler will accept the code as is.

PS. I also tried to override the type of the template method, but I could not do the job.

+4
source share
1 answer

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

The compiler analyzer otherwise assumes that Stack::StackEmptyException not a type and parses the code incorrectly (it cannot know what type it is because at that moment it does not know what type of Stack , so potentially StackEmptyException can also be a static element data). You should also usually search by reference instead of value.

+9
source

Source: https://habr.com/ru/post/1304074/


All Articles