捕获模板化异常时编译器错误

时间:2012-01-02 16:46:40

标签: c++ visual-studio-2010 templates exception c++-cli

这是我的通用异常及其基类,用本机C ++编写:

class DRAException : public std::exception {
public:
    DRAException( const std::string& what ) : std::exception( what.c_str() ) {}
    virtual ~DRAException( ){}
};

template<typename T>
class InvalidArgumentException : public DRAException{
    static std::string CreateErrorMessage( const std::string& argName, T value, boost::optional<T> min, boost::optional<T> max ){
        std::string& errorMessage = "Invalid argument value for " + argName + ": " + StringUtils::toString(value);
        if( min.is_initialized() )
            errorMessage += ". Min value: " + StringUtils::toString( min.get() );
        if( max.is_initialized() )
            errorMessage += ". Max value: " + StringUtils::toString( max.get() );
        return errorMessage;
    }
public:
    InvalidArgumentException( const std::string& argName, T value, boost::optional<T> min, boost::optional<T> max ) :
        DRAException( CreateErrorMessage(argName, value, min, max) ){ }
};

在C ++ / CLI程序集中,我定义了一个宏,它将本机异常映射到托管异常:

#define BEGIN_EXCEPTION_GUARDED_BLOCK \
    try {
#define END_EXCEPTION_GUARDED_BLOCK \
    \
    //Other catch clauses omitted for brevity's sake
    } catch( DRAExceptions::InvalidArgumentException ex ) { \
        throw gcnew System::ArgumentException( msclr::interop::marshal_as<System::String^>( ex.what() ) ); \
    }

然后我就这样使用它:

void MCImage::FindOptimalLut( Single% fWindow, Single% fLevel ) {
    BEGIN_EXCEPTION_GUARDED_BLOCK
    pin_ptr<Single> pWindow = &fWindow, pLevel = &fLevel;
    m_pNativeInstance->findOptimalLut( *pWindow, *pLevel );
    END_EXCEPTION_GUARDED_BLOCK
}

但是在尝试构建最后一段代码时,我收到了这个错误:

Image.cpp(72): error C2955: 'DRAExceptions::InvalidArgumentException' : use of class template requires template argument list
4>          d:\svn.dra.workingcopy\mcommon\../CommonCppLibrary/CustomExceptions.h(50) : see declaration of 'DRAExceptions::InvalidArgumentException'
4>Image.cpp(72): error C2316: 'DRAExceptions::InvalidArgumentException' : cannot be caught as the destructor and/or copy constructor are inaccessible

我无法在catch子句中专门化我的模板化类,因为这会破坏捕获所有特化的目的,无论类型如何。至于其他错误,构造函数和析构函数都是公共的,所以我不明白。我该如何解决这个问题?

PS:我刚开始使用Boost库,因此可以接受特定于Boost的解决方案

2 个答案:

答案 0 :(得分:3)

编译器准确地告诉您问题所在:

  

使用类模板需要模板参数列表

您无法在一次捕获中捕获每个可能的异常。您必须通过引用公共基类为每个不同的T捕获一个。

catch (const DRAException& Ex)

答案 1 :(得分:3)

您正在尝试使用类型模板,就像它是一种类型一样。它不是 - 只有模板的实例化类型。

您可以轻松解决问题。您的类根本不需要是模板 - 只有它的构造函数和CreateErrorMessage辅助函数需要是模板。