模板&元编程&编译期计算(96行)
2025-09-01 18:37:27
发布于:湖北
6阅读
0回复
0点赞
把小题大做运用到极致
#include <iostream>
#include <type_traits>
#include <utility>
template<typename T>
struct is_integer_like {
static constexpr bool value = std::is_integral<T>::value ||
std::is_same<T, long long>::value ||
std::is_same<T, unsigned long long>::value;
};
template<typename T, typename U>
typename std::enable_if<is_integer_like<T>::value && is_integer_like<U>::value, long long>::type
add_impl(T a, U b) {
return static_cast<long long>(a) + static_cast<long long>(b);
}
template<long long A, long long B>
struct ConstexprAdd {
static constexpr long long value = A + B;
};
template<typename... Args>
struct Sum;
template<typename First, typename... Rest>
struct Sum<First, Rest...> {
static long long value(First first, Rest... rest) {
return first + Sum<Rest...>::value(rest...);
}
};
template<>
struct Sum<> {
static long long value() { return 0; }
};
template<typename T, typename U>
decltype(auto) perfect_forward_add(T&& a, U&& b) {
return std::forward<T>(a) + std::forward<U>(b);
}
template<typename T, typename U>
struct result_type {
using type = decltype(std::declval<T>() + std::declval<U>());
};
template<typename Func, typename... Args>
auto exception_safe_invoke(Func&& func, Args&&... args)
-> typename std::result_of<Func(Args...)>::type {
try {
return std::forward<Func>(func)(std::forward<Args>(args)...);
} catch (...) {
throw std::runtime_error("Addition failed");
}
}
template<typename Derived>
class AdditionPolicy {
public:
template<typename T, typename U>
auto add(T a, U b) const {
return static_cast<const Derived*>(this)->impl_add(a, b);
}
};
class SafeAddition : public AdditionPolicy<SafeAddition> {
public:
template<typename T, typename U>
auto impl_add(T a, U b) const {
return a + b;
}
};
struct safe_tag {};
struct fast_tag {};
template<typename Tag>
struct addition_strategy;
template<>
struct addition_strategy<safe_tag> {
template<typename T, typename U>
static auto add(T a, U b) {
SafeAddition adder;
return adder.add(a, b);
}
};
template<>
struct addition_strategy<fast_tag> {
template<typename T, typename U>
static auto add(T a, U b) {
return a + b;
}
};
int main() {
long long a, b;
std::cin >> a >> b;
auto result1 = add_impl(a, b);
auto result2 = perfect_forward_add(a, b);
SafeAddition safe_adder;
auto result3 = safe_adder.add(a, b);
auto result4 = addition_strategy<fast_tag>::add(a, b);
auto result5 = exception_safe_invoke([](auto x, auto y) { return x + y; }, a, b);
static_assert(ConstexprAdd<1, 2>::value == 3, "Compile-time addition failed");
std::cout << result1;
return 0;
}
这里空空如也
有帮助,赞一个