简体   繁体   中英

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?

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);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM