c++11 - 基于#define变量类型的条件编译
问题描述
以下是我想要实现的剪辑版本。我正在对一个单词进行一些算术运算,我想__builtin_clrsb
在它可用并且用户int
用作单词类型时使用,否则使用慢速算法编译。__builtin_clrsb
无论类型如何,以下都会编译WORD
。
代码使用 C++11,但在嵌入式系统上运行,因此我无法访问大多数std::
设施。
#if !defined(WORD)
#define WORD int
#endif
template<size_t S, typename word = WORD>
class my_class {
...
...
...
size_t do_stuff(){
#if WORD == int && defined(__builtin_clrsb)
//compile with __builtin_clrsb
#else
//comple with slow method
#endif
}
};
解决方案
我认为你不应该这样做:
size_t do_stuff(){
#if WORD == int && defined(__builtin_clrsb)
//compile with __builtin_clrsb
#else
//comple with slow method
#endif
}
相反,您应该使用 C++ 模板专业化来解决这个问题。
template<class D, size_t S, class word>
struct my_class_do_stuff_impl {
D& self() { return *static_cast<D*>(this); }
D const& self() const { return *static_cast<D const*>(this); }
size_t do_stuff(){
//compile with slow method
//use `self()` instead of `this` to access members of `my_class`
}
};
#if defined(__builtin_clrsb)
template<class D, size_t S>
struct my_class_do_stuff_impl<D,S,int> {
D& self() { return *static_cast<D*>(this); }
D const& self() const { return *static_cast<D const*>(this); }
size_t do_stuff(){
//compile with __builtin_clrsb
//use `self()` instead of `this` to access members of `my_class`
}
};
#endif
template<size_t S, typename word = WORD>
class my_class:
public my_class_do_stuff_impl<my_class<S,word>, S, word>
{
// don't include do_stuff here
// if you call do_stuff, do this->do_stuff()
};
这样做有无数理由。一是WORD
int 并不强制 my_classword
成为int
. 另一个是我们可以在预处理器之外执行此操作,所以我们应该这样做。
推荐阅读
- java - 从 coord android 获取地址
- javascript - 检测用户是否安装了 Chrome 扩展程序
- swift - SQLite 绑定文本值与检索到的文本值不同
- python - 如何优化此 Python 代码?
- php - 使用数据库登录 Symfony
- reactjs - 如何为 React Material UI 实现全局主题?
- javascript - javascript xmlhttprequest 总是获得状态 0
- c++ - c ++:为什么整数前面的减号信号会给出一个疯狂的数字?
- django - Django allauth 出错 is_safe_url() got an unexpected keyword argument 'allowed_hosts'
- c - STM32 VCP驱动——指针失效只有优化