【发布时间】:2018-10-27 21:04:56
【问题描述】:
我有一些遗留代码使用函数指针数组来模拟内存处理程序。
所以我现在正在尝试使用模板来获得相同的功能。
到目前为止,这是我尝试过的:
template <typename R, typename ...ARGS> using function = R(*)(ARGS...);
template<size_t Size> using ReadType = function<SizedUInt<Size>, const uint32_t>;
// arrays to redeclare
std::array<ReadType<8>, memory_handler_size> read_8_handler_;
std::array<ReadType<16>, memory_handler_size> read_16_handler_;
std::array<ReadType<32>, memory_handler_size> read_32_handler_;
template<size_t Size>
void initializeReadHandler(uint32_t begin,
uint32_t end,
ReadType<Size> func) {
begin >>= 16;
end >>= 16;
for (uint32_t current = begin; current <= end; ++current) {
//read_handler_[current & 0xFFFF] = func;
}
}
如何声明读取处理程序数组以便使用模板化的initializeReadHandler() 函数对其进行初始化?
我不想使用std::function,因为我负担不起性能开销...
...编辑...
这是基于 Yakk 的回答、max66 备注和一些小修复(错字等)的代码:
template <typename R, typename ...ARGS> using function = R(*)(ARGS...);
template<size_t S> using ReadType = function<SizedUInt<S>, const uint32_t>;
template<class ReadType>
using ReadHandlerType = std::array<ReadType, memory_handler_size>;
ReadHandler<8> read_8_handler_;
ReadHandler<16> read_16_handler_;
ReadHandler<32> read_32_handler_;
template<size_t S>
void initializeReadHandler(uint32_t begin,
uint32_t end,
ReadType<S> func) {
begin >>= 16;
end >>= 16;
auto t = std::tie(read_8_handler_, read_16_handler_, read_32_handler_);
for (uint32_t current = begin; current <= end; ++current) {
auto& handler = std::get < ReadHandler<S>& >(t);
handler[current & 0xFFFF] = func;
}
}
像魅力一样工作:D 谢谢大家!
【问题讨论】:
-
这对我来说很好,你有什么特别的问题吗?
-
其实我不知道如何在注释行中选择正确的数组...
标签: c++ c++11 templates c++14 c++17