cai-jinlin commented on PR #59014:
URL: https://github.com/apache/doris/pull/59014#issuecomment-3663346499
#ifndef CORE_HPP
#define CORE_HPP
#include <string>
// 核心计算函数
inline int64_t hamming_calc(const std::string& s1, const std::string& s2) {
if (s1.length() != s2.length()) {
throw std::runtime_error("length mismatch");
}
int64_t diff = 0;
for (size_t i = 0; i < s1.length(); i++) {
if (s1[i] != s2[i]) diff++;
}
return diff;
}
#endif
//选择能抛出异常的模版
#ifndef TEMPLATE_HPP
#define TEMPLATE_HPP
class FunctionBinaryToType {
public:
static int64_t call(const std::string& s1, const std::string& s2) {
// 这里起作用:它会调用核心函数
// 如果 hamming_calc 抛出异常,这里会让异常继续传播
return hamming_calc(s1, s2);
}
};
// 选择模板:这里 FunctionBinaryToType 被选中
using HammingDistance = FunctionBinaryToType;
#endif
//测试代码
#include <iostream>
#include "template.hpp"
// 用户调用的函数
int64_t hamming_distance(const std::string& s1, const std::string& s2) {
return HammingDistance::call(s1, s2);
}
int main() {
// 正常情况
std::cout << "1. 正常调用: ";
try {
int64_t r = hamming_distance("abc", "abc");
std::cout << "结果 = " << r << "\n";
} catch (...) {
std::cout << "抛出异常\n";
}
// 错误情况
std::cout << "\n2. 长度不同: ";
try {
int64_t r = hamming_distance("abc", "abcd");
std::cout << "结果 = " << r << "\n";
} catch (const std::exception& e) {
std::cout << "抛出异常: " << e.what() << "\n";
}
std::cout << "\nFunctionBinaryToType 的作用:传递异常\n";
return 0;
}
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]