我正在为 boost
编写一个包装器numeric_cast
与包装函数类似:
#include <boost/numeric/conversion/cast.hpp>
#include <stdexcept>
template <typename Source, typename Target>
Target numeric_cast(Source src)
{
try
{
// calling boost numeric_cast here
}
catch(boost::numeric::bad_numeric_cast& e)
{
throw std::runtime_error("numeric_cast failed, fromType: " + Source + " toType: " + Target);
}
}
我遇到了这个错误:
error: expected primary-expression before ‘(’ token
throw std::runtime_error("numeric_cast failed ...
^
我认为错误是要求处理 Source
和Target
在错误消息中。那么有没有办法打印template
typename
?我是 C++ 的初学者,所以这可能是一个愚蠢的问题......
最佳答案
您可以使用typeid(T).name()
获取模板参数的原始字符串:
#include <boost/numeric/conversion/cast.hpp>
#include <stdexcept>
#include <typeinfo>
template <typename Source, typename Target>
Target numeric_cast(Source src)
{
try
{
// calling boost numeric_cast here
}
catch(boost::numeric::bad_numeric_cast& e)
{
throw (std::string("numeric_cast failed, fromType: ") +
typeid(Source).name() + " toType: " + typeid(Target).name());
}
}
请注意,字符串文字 "numeric_cast failed, fromType:"
应为 std::string
类型以支持 '+'
运算符.
关于c++ - 如何在 C++ 中打印模板类型名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69463047/