@
ysc3839 #56 我的,让 chatgpt 生成后感觉差不多就发了,上班摸鱼修改了下:
```
#include <cstdint>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
class BaseClass {
public:
virtual ~BaseClass() = default;
virtual void print() = 0;
};
std::map<uint32_t, BaseClass *> reg;
template <std::uint32_t N> struct myclass : public BaseClass {
void print() override {
throw std::logic_error("Error: myclass<" + std::to_string(N) +
"> is not specialized.");
}
};
template <uint32_t N> void register_classes() {
reg[N] = new myclass<N>();
if constexpr (N > 0) {
register_classes<N - 1>();
}
}
template <> struct myclass<0x1ff> : public BaseClass {
void print() override { std::cout << "Specialized myclass<1f0>\n"; }
};
template <> struct myclass<0x1fa> : public BaseClass {
void print() override { std::cout << "Specialized myclass<2f0>\n"; }
};
// 通用模板函数
void foo(BaseClass *obj) {
obj->print(); // 调用特化模板的成员函数(如果有)
}
// 通用函数:根据运行时输入调用特定模板
void invoke_function(std::string_view hex_input) {
// 将字符串解析为 16 进制数值
std::uint32_t num;
std::stringstream ss;
ss << std::hex << hex_input;
ss >> num;
foo(reg[num]);
}
// 主程序
int main() {
register_classes<0xfff>();
try {
invoke_function("1ff");
invoke_function("1fa");
invoke_function("3f0");
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << '\n';
}
for (auto &pair : reg) {
delete pair.second;
}
return 0;
}
```
还是写特化模板就行,编译时给编译器传一个参数:-ftemplate-depth=4096 ;