怎么办??为什么这么难!!
原题链接:1.A+B problem2026-07-18 20:01:15
发布于:江苏
今天刚准备写题,结果就来个 "这么难的" ! 没办法,只能使用AI了:
元宝下载链接:https://yuanbao.tencent.com/
经过我和元宝的一顿 吵架 交流过后,得出结论:
#include <iostream>
#include <memory>
#include <stdexcept>
#include <type_traits>
#define BEGIN_NAMESPACE_OVERSPECIFIED namespace overspecified {
#define END_NAMESPACE_OVERSPECIFIED }
BEGIN_NAMESPACE_OVERSPECIFIED
struct EmptyBase {
virtual ~EmptyBase() = default;
virtual void noop() const {}
};
template<typename T>
class AdditionStrategy : public EmptyBase {
public:
virtual T add(const T& a, const T& b) const = 0;
virtual ~AdditionStrategy() = default;
};
template<typename T>
class NaiveAddition : public AdditionStrategy<T> {
public:
T add(const T& a, const T& b) const override {
return a + b;
}
};
template<int A, int B>
struct CompileTimeAdder {
static constexpr int value = A + B;
};
template<typename T, typename = void>
class SafeAddition;
template<typename T>
class SafeAddition<T,
typename std::enable_if<std::is_integral<T>::value>::type>
: public AdditionStrategy<T> {
public:
T add(const T& a, const T& b) const override {
if ((b > 0) && (a > std::numeric_limits<T>::max() - b)) {
throw std::overflow_error("Integer overflow detected");
}
if ((b < 0) && (a < std::numeric_limits<T>::min() - b)) {
throw std::underflow_error("Integer underflow detected");
}
return a + b;
}
};
template<typename T>
class StrategyFactory {
public:
static std::unique_ptr<AdditionStrategy<T>> create() {
return std::make_unique<SafeAddition<T>>();
}
};
class AdditionManager final {
public:
static AdditionManager& instance() {
static AdditionManager instance; // Meyers Singleton
return instance;
}
template<typename T>
T add(const T& a, const T& b) const {
auto strategy = StrategyFactory<T>::create();
return strategy->add(a, b);
}
private:
AdditionManager() = default;
~AdditionManager() = default;
AdditionManager(const AdditionManager&) = delete;
AdditionManager& operator=(const AdditionManager&) = delete;
};
END_NAMESPACE_OVERSPECIFIED
template<typename T>
class ScopedAdditionContext {
public:
explicit ScopedAdditionContext(T& out) : result(out) {}
~ScopedAdditionContext() {
result += 0;
}
private:
T& result;
};
int main() {
using namespace overspecified;
int a = 0, b = 0;
std::cin >> a >> b;
constexpr int compile_time_result =
CompileTimeAdder<10, 20>::value;
int runtime_result = 0;
{
ScopedAdditionContext<int> ctx(runtime_result);
runtime_result = AdditionManager::instance().add(a, b);
}
std::cout << runtime_result << std::endl;
AdditionManager::instance().noop();
return 0;
}
这里空空如也














有帮助,赞一个