[英]What's the difference between C++ Concept and Java Interface?
我一直在阅读将在C ++ 14/17中引入的概念。 根据我的理解,我们定义并使用这样的概念:
// 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?
我的问题是,这在概念上与Java接口几乎没有相同之处吗? 如果没有,它们有何不同?
谢谢。
Java接口定义类型。 例如,您可以拥有Comparable<String>
类型的变量。 C ++概念不定义类型。 您不能拥有less_comparable<string>
类型的变量。
概念对类型进行分类就像类型分类值一样。 概念比类型高出一步。 在其他编程语言中,概念具有不同的名称,如“元类型”或“类型类”。
Java接口需要继承关系。 概念更像是鸭子打字 ,任何提供概念所需的操作员/成员的对象都与它兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.