Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 225
nav Avatar asked Mar 02 '14 10:03

nav


People also ask

Which is better C or Java?

C is a procedural, low level, and compiled language. Java is an object-oriented, high level, and interpreted language. Java uses objects, while C uses functions. Java is easier to learn and use because it's high level, while C can do more and perform faster because it's closer to machine code.

What is interface concept in Java?

An interface is an abstract "class" that is used to group related methods with "empty" bodies: To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ).

What is difference between C C++ and Java?

Answer: The main difference between C++ and Java is that C++ is only a compiled language while Java is both compiled and interpreted. The C++ compiler converts the source code into machine code and therefore, it is platform dependent.

What is the difference between Java class and interface?

Differences between a Class and an Interface:A class can be instantiated i.e, objects of a class can be created. An Interface cannot be instantiated i.e, objects cannot be created. Classes does not support multiple inheritance. Interface supports multiple inheritance.


1 Answers

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".

like image 197
fredoverflow Avatar answered Sep 19 '22 04:09

fredoverflow