[英]Adding methods to class template specialization
I would like to achieve behaviour present in STL: when we look at a vector container, it is known that it has vector<bool>
specialization which adds method flip()
.我想实现 STL 中存在的行为:当我们查看向量容器时,已知它具有vector<bool>
专门化,它添加了方法flip()
。
Is it possible to achieve such class extension without copying the whole class as a specialization and adding new method in its body?是否可以在不复制整个类作为特化并在其主体中添加新方法的情况下实现此类扩展?
I suppose you can write the specialization so it inherit from the generic version.我想您可以编写专业化,以便它从通用版本继承。
By example: suppose you have a struct foo
with a type and a value (with default value) template parameters;例如:假设您有一个带有类型和值(具有默认值)模板参数的struct foo
; suppose it has some methods ( bar()
, in the following example)假设它有一些方法( bar()
,在下面的例子中)
template <typename, bool = true>
struct foo
{ void bar () {}; };
and suppose you want a specialization for bool
(as template type) with the same methods and an additional baz()
;并假设您想要使用相同的方法和额外的baz()
对bool
(作为模板类型)进行专业化; you can inherit foo<bool>
from the general version as follows你可以从普通版本继承foo<bool>
如下
template <>
struct foo<bool> : public foo<bool, false>
{ void baz () {}; };
You can verify that你可以验证
foo<int> fi;
fi.bar(); // compile
//fi.baz(); // compilation error
foo<bool> fb;
fb.bar(); // compile
fb.baz(); // compile
You can SFINAE the method of "specialization"你可以SFINAE“专业化”的方法
template <typename T>
class C
{
public:
// Common code...
template <typename U = T, std::enable_if_t<std::is_same<bool, U>::value, bool> = false>
void only_for_bool() {/*..*/}
};
C++20 would allow better syntax: C++20 将允许更好的语法:
template <typename T>
class C
{
public:
// Common code...
void only_for_bool() requires (std::is_same<bool, T>::value) {/*..*/}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.