面试题答案
一键面试#include <iostream>
#include <type_traits>
// 基础模板类Base
template <typename T>
class Base {
public:
T value;
Base(T val) : value(val) {}
};
// 从Base<T>派生的模板类Derived
template <typename T>
class Derived : public Base<T> {
public:
using Base<T>::Base;
template <typename U>
T convertAndAdd(const Base<U>& other) {
static_assert(std::is_arithmetic<T>::value && std::is_arithmetic<U>::value, "T and U must be arithmetic types");
return this->value + static_cast<T>(other.value);
}
};
// Derived<bool>特化实现
template <>
class Derived<bool> : public Base<bool> {
public:
using Base<bool>::Base;
bool convertAndAdd(const Base<bool>& other) {
return this->value != 0 || other.value != 0;
}
};
你可以使用如下方式测试:
int main() {
Derived<int> derivedInt(5);
Base<double> baseDouble(3.5);
std::cout << "Int + Double: " << derivedInt.convertAndAdd(baseDouble) << std::endl;
Derived<bool> derivedBool(true);
Base<bool> baseBool(false);
std::cout << "Bool + Bool: " << (derivedBool.convertAndAdd(baseBool)? "true" : "false") << std::endl;
return 0;
}