Miq*_*uel 6 c++ templates template-specialization
我想为BASECLASS和所有派生类都有一个特殊的格式化程序.我有以下课程:
struct BASECLASS { ... };
struct SPECIALFORMAT : BASECLASS { ... }
struct ANOTHERSPECIALFORMAT : BASECLASS { ... }
template <class T>
struct LISTFORMATTER {
list<T> l;
bool format() {
};
}
bool LISTFORMATTER<BASECLASS>::format() { ... }
LISTFORMATTER<BASECLASS> bcFt;
LISTFORMATTER<SPECIALFORMAT> spFt;
LISTFORMATTER<ANOTHERSPECIALFORMAT> aspFt;
bcFt.format(); // <-- ok
spFt.format(); // <-- Calling standard format(), not specialized
aspFt.format(); // <-- Calling standard format(), not specialized
Run Code Online (Sandbox Code Playgroud)
如何为基类和所有继承的类专门化方法?
编辑更喜欢不使用提升.c ++(不是c ++ 11)
首先,您需要is_base_of
. 如果您不想使用 Boost 或 C++11,请在此处获取一个:
`is_base_of` 是如何工作的?
然后,你可以这样做:
template <bool B> struct bool_ {};
// ...
bool format() { do_format(bool_<is_base_of<BASECLASS, T>::value>()); }
bool do_format(bool_<false>) {
// not inheriting BASECLASS
}
bool do_format(bool_<true>) {
// inheriting BASECLASS
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,AFAIK,没有办法非侵入性地做到这一点,即简单地通过添加专业化。
编辑:实际上,你可以在没有 is_base_of 的情况下做到这一点:
// ...
bool format() { do_format((T*)0); }
bool do_format(void*) { /* not inheriting */ }
bool do_format(BASECLASS*) { /* inheriting */ }
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为派生->基是比类->空更好的转换。
归档时间: |
|
查看次数: |
4648 次 |
最近记录: |