C++ Concept和Java Interface之间有什么区别?

nav*_*nav 6 c++ 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?
Run Code Online (Sandbox Code Playgroud)

我的问题是,这在概念上与Java接口几乎没有相同之处吗?如果没有,它们有何不同?

谢谢.

fre*_*low 9

Java接口定义类型.例如,您可以拥有一个类型的变量Comparable<String>.C++概念定义类型.你不能有一个类型的变量less_comparable<string>.

概念类型进行分类就像类型分类值一样.概念比类型高出一步.在其他编程语言中,概念具有不同的名称,如"元类型"或"类型类".

  • +1表示"概念分类类型就像类型分类值". (2认同)