[英]What's the difference between C++ Concept and Java Interface?
I've been doing some reading on Concepts that are going to be introduced in C++14/17. 我一直在阅读将在C ++ 14/17中引入的概念。 From what I understood, we define and use a concept like this:
根据我的理解,我们定义并使用这样的概念:
// Define the concept (from wikipedia)
auto concept less_comparable<typename T> {
bool operator<(T);
}
// A class which implements the requirements of less_comparable,
// with T=`const string &`
class mystring
{
bool operator < (const mystring & str) {
// ...
}
};
// Now, a class that requires less_comparable
template <less_comparable T>
class my_sorted_vector
{
// ...
};
// And use my_sorted_vector
my_sorted_vector<int> v1; // should be fine
my_sorted_vector<mystring> v2; // same
my_sorted_vector<struct sockaddr> v3; // must give error?
My question is, isn't this conceptually pretty much the same as a Java Interface? 我的问题是,这在概念上与Java接口几乎没有相同之处吗? If not, how are they different?
如果没有,它们有何不同?
Thanks. 谢谢。
Java interfaces define types. Java接口定义类型。 For example, you can have a variable of type
Comparable<String>
. 例如,您可以拥有
Comparable<String>
类型的变量。 C++ concepts do not define types. C ++概念不定义类型。 You cannot have a variable of type
less_comparable<string>
. 您不能拥有
less_comparable<string>
类型的变量。
Concepts classify types just like types classify values. 概念对类型进行分类就像类型分类值一样。 Concepts are one step above types.
概念比类型高出一步。 In other programming languages, concepts have different names like "meta-types" or "type classes".
在其他编程语言中,概念具有不同的名称,如“元类型”或“类型类”。
Java interfaces require an inheritance relation. Java接口需要继承关系。 Concepts act more like duck typing , any object that provides the operators/members required by a concept is compatible with it.
概念更像是鸭子打字 ,任何提供概念所需的操作员/成员的对象都与它兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.