在C ++中键入静态鸭子 [英] Static duck typing in C++
问题描述
对于由模板参数指定的类型,C ++具有某种形式的鸭子类型.我们不知道 DUCK1
和 DUCK2
是什么类型,但是只要它们可以 quack()
,它将编译并运行:
C++ has some sort of duck typing for types given by template parameters. We have no idea what type DUCK1
and DUCK2
will be, but as long as they can quack()
, it will compile and run:
template <class DUCK1, class DUCK2>
void let_them_quack(DUCK1* donald, DUCK2* daisy){
donald->quack();
daisy->quack();
}
但是写起来有点不方便.当我完全不在乎 DUCK1
和 DUCK2
的实际类型,而是想充分利用鸭子类型的想法时,我想与上面的内容略有不同:
But it's a bit inconvenient to write. When I do absolutely not care what actual types DUCK1
and DUCK2
are but rather want to fully use the idea of duck typing, then I would like to have something sligthly different than above:
- 我想省略写一个重复且几乎毫无意义的模板参数列表(试想一下,如果有7只鸭子……会发生什么事情……)
- 我想更明确一点,就是永远不要使用类型,而只有接口才是重要的.
- 我想要某种界面注释/检查.以某种方式弄清楚该类型后面应有什么接口.(不过,这与鸭子的打字方式有所不同.)
C ++是否提供任何功能来实现这三个想法中的一个或多个?
(我知道在大多数情况下,虚拟继承是实现这种模式的一种选择方法,但是这里的问题是关于静态多态的情况.)
(I know that virtual inheritance is the method of choice in most cases to implement such patterns, but the question here is specifically about the case of static polymorphism.)
推荐答案
关于问题1和问题2:由于C ++ 14,您可以省略显式的 template< typename ...
样板,并使用 auto
,但仅适用于lambda:
Concerning questions 1 and 2: since C++14 you can omit explicit template <typename ...
boilerplate and use auto
, but only in lambdas:
auto let_them_quack = [] (auto & donald, auto & daisy){
donald.quack();
daisy.quack();
};
(是的,我更喜欢引用指针).GCC允许在通常的功能中将其作为扩展.
(yes, I prefer references to pointers). GCC allows to do so in usual functions as an extension.
对于问题3,您在说什么被称为概念.它们在C ++中存在了很长时间,但只是作为文档术语.现在,概念TS 正在进行中,可让您编写类似
For the question 3, what you are talking about are called concepts. They existed in C++ for a long time, but only as a documentational term. Now the Concepts TS is in progress, allowing you to write something like
template<typename T>
concept bool Quackable = requires(T a) {
a.quack();
};
void let_them_quack (Quackable & donald, Quackable & daisy);
请注意,它还不是C ++,只有一个技术规范正在进行中.不过,GCC 6.1似乎已经支持它.使用当前的C ++可以实现概念和约束.您可以在 boost 中找到一个.
Note that it is not yet C++, only a technical specification in progress. GCC 6.1 already seems to support it, though. Implementations of concepts and constraints using current C++ are possible; you can find one in boost.
这篇关于在C ++中键入静态鸭子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!