gpt4 book ai didi

c++ - 从 C++ 中的基实例获取派生类的类型名

转载 作者:太空宇宙 更新时间:2023-11-04 11:54:45 24 4
gpt4 key购买 nike

我正在为 C++ 项目创建通用错误处理程序。作为日志记录的一部分,我想包括异常类的名称。我希望有一种方法可以从 std::exception 实例中通用地获取特定错误类的名称,而不必使用 dynamic_cast 和逻辑树。

例子:

exception_handler.h

#pragma once

#include <exception>
#include <string>

class ExceptionHandler
{
public:
static std::string get_exception_type_name(std::exception ex)
{
return ((std::string)typeid(ex).name()).substr(11);
}
};

main.cpp

#include <iostream>
#include "exception_handler.h"

int _tmain(int argc, _TCHAR* argv[])
{
std::string any = "any";
std::out_of_range ex("Out of range exception");

std::cout << ExceptionHandler::get_exception_type_name(ex) << std::endl;

std::cout << "Press any key to close this window..." << std::endl;
std::cin >> any;
}

执行输出“异常”。我希望它说“out_of_range”或我输入函数的任何其他类型的派生异常。

提前致谢。

最佳答案

参数是sliced .通过 const& 而不是通过值传递:

static std::string get_exception_type_name(std::exception const& ex)
{ //^^^^^^
return typeid(ex).name();
}

参见 http://ideone.com/LWoxgm例如。

关于c++ - 从 C++ 中的基实例获取派生类的类型名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16612020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com