...

/

Full Example of Interface

Full Example of Interface

Let's see a complete example of the interface using requirements.

Example with no constraints on the exponent

Let’s have a look at the full example below:

Press + to interact
#include <cmath>
#include <iostream>
#include <string>
#include <concepts>
#include <type_traits>
template <typename Base, typename Exponent>
concept HasPower = std::convertible_to<Exponent, int> &&
requires (Base base, Exponent exponent) {
base.power(exponent);
};
//class having a conversion operator
class IntWithPower {
public:
IntWithPower(int num) : m_num(num) {}
int power(IntWithPower exp) {
return pow(m_num, exp);
}
operator int() const { return m_num; }
private:
int m_num;
};
//function on which concept is applied
template<typename Exponent>
void printPower(HasPower<Exponent> auto number, Exponent exponent) {
std::cout << number.power(exponent) << '\n';
}
int main() {
printPower(IntWithPower{5}, IntWithPower{4});
printPower(IntWithPower{5}, 4L);
printPower(IntWithPower{5}, 3.0);
}

The concept HasPower expects two template parameters, Base and Exponent, and has two explicit constraints:

  • Using the concept defined on line 8, Exponent
...