c++ - 如何在 C++ 中打印模板类型名?

标签 c++ templates typename

我正在为 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 ...
                          ^

我认为错误是要求处理 SourceTarget在错误消息中。那么有没有办法打印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());
    }
}

Demo.

请注意,字符串文字 "numeric_cast failed, fromType:" 应为 std::string 类型以支持 '+' 运算符.

关于c++ - 如何在 C++ 中打印模板类型名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69463047/

相关文章:

django - 我如何在 Django 模板中将整数的 unix 时间戳转换为人类可读的格式?

c++ - 类 - 命名空间和模板成员函数特化

c++ - 在 C++ 中过滤类型名

函数: "illegal use of explicit template arguments"的C++模板特化

c++ - 说 C++ 中的数组或 Python 中的列表是类是否正确?数据结构?或两者?

C++ 声明中的两种或多种数据类型

c++ - 未识别 libtool 和 autoconf 的 LT_VERSION

c++ - 在容器中存储多重继承对象

c++ - int* 的默认值是 NULL 吗?

c++ - 为什么 'typedef' 这个词后面需要 'typename' 作为依赖类型?