gpt4 book ai didi

基类的c++模板特化

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:27:34 24 4
gpt4 key购买 nike

我想要一个用于 BASECLASS 和所有派生类的特殊格式化程序。我有以下类(class):

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

如何为基类和所有继承类特化一个方法?

编辑 最好不要使用 boost。 C++(不是 C++11)

最佳答案

首先,您需要is_base_of。如果您不想使用 Boost 或 C++11,请在此处获取一个: How does `is_base_of` work?

然后,你可以这样做:

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
}

顺便说一句,AFAIK,没有办法以非侵入式的方式做到这一点,即简单地通过添加特化。

编辑:实际上,您可以在没有 is_base_of 的情况下完成:

// ...
bool format() { do_format((T*)0); }
bool do_format(void*) { /* not inheriting */ }
bool do_format(BASECLASS*) { /* inheriting */ }

这是有效的,因为 derived->base 是比 class->void 更好的转换。

关于基类的c++模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21437730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com