简体   繁体   中英

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. 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? If not, how are they different?

Thanks.

Java interfaces define types. For example, you can have a variable of type Comparable<String> . C++ concepts do not define types. You cannot have a variable of type 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. Concepts act more like duck typing , any object that provides the operators/members required by a concept is compatible with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM