这是我的通用异常及其基类,用 native 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 程序集中,我定义了一个将 native 异常映射到托管异常的宏:
#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 子句中特化我的模板化类,因为那样会破坏捕获所有特化而不管类型的目的。至于另一个错误,构造函数和析构函数都是公共(public)的,所以我不明白。我该如何解决这个问题?
PS:我刚开始使用 Boost 库,因此可以接受特定于 Boost 的解决方案
最佳答案
您正在尝试将类型模板当作类型来使用。它不是 - 只有模板的实例化是类型。
您可以轻松解决您的问题。您的类根本不需要是模板 - 只有它的构造函数和 CreateErrorMessage
辅助函数需要是模板。
关于c++ - 捕获模板化异常时的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8703260/