1

these two pieces of example code do the same job, and both make sense to me. So when should I use concept and when to use interface?

IMHO using interface requires to explicitly create the abstract class and inherit from it, what's the necessity to use interface?

might be a silly question but I'm really curious.

template<class T>
concept HasVolume =
requires(T t){{ t.volume() }; };

template<HasVolume V>
int PrintVolumeConcept(V v)
{
    cout << v.volume() << endl;
    return v.volume();
}

class Cube
{
public:
    int side;

    int volume() const
    { return side * side * side; }
};
class HasVolume
{
public:
    virtual int volume() const = 0;
};

class Cube : public HasVolume
{
public:
    int side;

    int volume() const
    { return side * side * side; }
};

int PrintVolume(const HasVolume& v)
{
    cout << v.volume() << endl;
    return v.volume();
}
Yuwei Xu
  • 433
  • 3
  • 5
  • One important reason to use concepts is because of speed, in high performance applications. Because calling virtual-interfaced functions takes more time. Concept based classes are usually templated classes and their functions are all inlined, that's why they are more optimized and have less running time. – Arty Jan 08 '21 at 07:50
  • 1
    Related: https://stackoverflow.com/questions/16586489/c-interface-vs-template – Lukas-T Jan 08 '21 at 07:52
  • 1
    The difference is not in acheiving an effect, but the associated costs. – StoryTeller - Unslander Monica Jan 08 '21 at 08:36

0 Answers0