template<typename T>
class A {}
How can I restrict types T to only those that are copy-assignable? I know about std::is_copy_assignable<T>::value
but how can I use that to restrict the type T for class A?
You can also use static_assert
for this, which lets you generate a nicer error message:
template<typename T>
class A
{
static_assert (std::is_copy_assignable_v<T>, "T must be copy-assignable");
};
You can use std::enable_if
like this:
template<typename T,
typename = std::enable_if_t<std::is_copy_assignable_v<T>, void>>
class A {};
Here's a demo on Compiler Explorer using the following code:
#include<type_traits>
#include<ostream>
template<typename T,
typename = std::enable_if_t<std::is_copy_assignable_v<T>, void>>
class A {};
int main() {
A<int> a;
// A<std::ostream> b; // error
}
In c++20, you could write:
template<typename T>
requires std::is_copy_assignable_v<T>
class A {};
which is easier to read, and produces a better error message.
And here's a demo of that:
#include<type_traits>
#include<ostream>
template<typename T>
requires std::is_copy_assignable_v<T>
class A {};
int main() {
A<int> a;
// A<std::ostream> b; // error
}
If you'd like to create your own type constraint structures from scratch, without relying even on C++11, that are still simple, easily readable, have no performance overhead and ensure a comprehensive compiler message in case of an error, you can get inspired by Bjarne Stroustrup .
For example, you can enforce the copy-assignability constraint by deriving your class from the following structure or constructing it in a function:
template<class T1, class T2> struct Can_copy {
static void constraints(T1 a, T2 b) { T2 c = a; b = a; }
Can_copy() { void(*p)(T1,T2) = constraints; }
};
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.