gpt4 book ai didi

c++ - 无法捕获模板特化方法抛出的异常

转载 作者:行者123 更新时间:2023-12-04 17:19:43 25 4
gpt4 key购买 nike

假设我有以下代码:

//handler.hpp
template<typename T>
class handler
{
private:
static void process_core(const T& request) { }
public:
static void process(const T& request)
{
try
{
process_core(request);
}
catch(const std::exception& e)
{
std::cout << "exception " << e.what() << std::endl;
}
}
};

//string_handler.cpp
template<> void handler<std::string>::process_core(const std::string& s)
{
std::cout << "string_handler" << std::endl;
throw std::invalid_argument("bang");
}

//test.cpp
int main()
{
handler<std::string>::process("123");
}

我认为应该捕获并处理 std::invalid_arguemnt 异常,但事实并非如此。程序崩溃:

string_handler
terminate called after throwing an instance of 'std::invalid_argument'
what(): bang
Aborted (core dumped)

有趣的是:

  1. 将方法 handler::process_core 更改为

    static void process_core(const T& request);  // { } braces are removed

有效。但是我不能这样做,因为 process_core 对于某些类型是可选的。 Q1:为什么摘牙套后还能用?

  1. 将源代码合并到一个文件中(比如 test.cpp)是可行的。 Q2:为什么?

  2. Q3:正确的实现方式是什么?

最佳答案

你应该在 main 中使用它之前声明你的特化,否则你的程序是错误的。 (您有冲突的常规实例化和特化之一)。

  • 当删除带有“1.”的定义时,您没有定义冲突。
  • 当合并到一个文件中时,您在常规实例化之前声明(并定义)专业​​化,所以也可以。
  • 允许在不同文件中拆分的方法是声明特化,因此:

    //handler.hpp

    template<typename T>
    class handler
    {
    // ...
    };

    // Declare specialization
    template<> void handler<std::string>::process_core(const std::string& s);

关于c++ - 无法捕获模板特化方法抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47969251/

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