Home > OS >  C : How to enforce the templated type to implement a certain operator(s)?
C : How to enforce the templated type to implement a certain operator(s)?

Time:12-10

There was a similar question from 9 years ago (C 11) and maybe the newer standards provide this.

I would like to make sure that the templated class I am writing can be instantiated only if the type used implements certain operators, for example <.

template <typename T>
class XX {
private:
    T foo;
public:
    bool continiumTransfunctioneer(const T zoo){return zoo < foo;}
    // ...
};

I know that the code will fail to compile if that requirement is not met but the messages from the compiler can be quite verbose-I would like to be able to forewarn the users.

CodePudding user response:

This is a good use case for using C 20 concepts:

template <typename T>
  requires requires (const T& x, const T& y) { x < y; }
class XX {
 private:
  T foo;
 public:
  bool continiumTransfunctioneer(const T& zoo) const { return zoo < foo; }
};

Demo.

  • Related