JHeni
JHeni

Reputation: 751

C++20 Concepts Apply constraint on templated function

I'd like to start with c++20 concepts.

class MyClass
{
  template<typename T>
  void copy(const T& data);
};

copy() only works if T is is_trivially_copyable. Before C++20 I'd have used

static_assert(is_trivially_copyable<T>, "Type must be trivially copyable");

within the copy function.

But from my understanding, this is an issue where concepts can be used. After some googling I came up with

template <typename T>
concept isTriviallyCopyable = std::is_trivially_copyable_v<T>;

however when adding this to the function

class MyClass
{
  template<isTriviallyCopyable>
  void copy(const isTriviallyCopyable & data);
};

This gives me a compiler error. Could you help me out here?

Upvotes: 0

Views: 103

Answers (1)

NathanOliver
NathanOliver

Reputation: 180500

You need to add a type parameter for your sTriviallyCopyable to be applied to. That would give you

class MyClass
{
    template<isTriviallyCopyable T>
    void copy(const T & data);
};

Upvotes: 4

Related Questions