Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Concepts are for compile-time polymorphism, That means parametric generic code. Interfaces are for run-time polymorphism. </p> <p>You have to implement an interface as you implement a Concept. The difference is that you don't have to explicitly say that you are implementing a Concept. If the required interface is matched then no problems. In the case of interfaces, even if you implemented <strong>all</strong> the required functions, you have to excitability say that you are implementing it!</p> <hr> <p>I will try to clarify my answer :)</p> <p>Imagine that you are designing a container that accepts any type that has the <strong>size</strong> member function. We formalize the Concept and call it HasSize, of course we should define it elsewhere but this is an example no more.</p> <pre><code>template &lt;class HasSize&gt; class Container { HasSize[10]; // just an example don't take it seriously :) // elements MUST have size member function! }; </code></pre> <p>Then, Imagine we are creating an instance of our <strong>Container</strong> and we call it <strong>myShapes</strong>, Shape is a base class and it defines the <strong>size</strong> member function. Square and Circle are just children of it. If Shape didn't define size then an error should be produced.</p> <pre><code>Container&lt;Shape&gt; myShapes; if(/* some condition*/) myShapes.add(Square()); else myShapes.add(Circle()); </code></pre> <p>I hope you see that Shape can be checked against <strong>HasSize</strong> at <em>compile time</em>, there is no reason to do the checking at run-time. Unlike the elements of <strong>myShapes</strong>, we could define a function that manipulates them :</p> <pre><code>void doSomething(Shape* shape) { if(/* shape is a Circle*/) // cast then do something with the circle. else if( /* shape is a Square */) // cast then do something with the square. } </code></pre> <p>In this function, you can't know what will be passed till run-time a Circle or a Square!</p> <p>They are two tools for a similar job, though Interface-or whatever you call them- can do almost the same job of Concepts at run-time but you lose all benefits of compile-time checking and optimization!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload