I try to use a constraint for a class specialization:
struct A {};
struct B {};
struct C {};
template<typename T>
concept bool AorB() {
return std::is_same<T, A>::value || std::is_same<T, B>::value;
}
template<typename T>
class X {};
template<AorB T>
class X {};
int main() {
X<A> x1; // error: redeclaration 'template<class T> class X' with different constraints class X {};
X<B> x2;
X<C> x3;
}
I don't know if I am making a mistake here or if this generally won't be possible?
What could be alternatives to this approach? I could make to specializations using CRTP to a common base template, but thats looks ugly to me.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
A constraint is a requirement that types used as type arguments must satisfy. For example, a constraint might be that the type argument must implement a certain interface or inherit from a specific class. Constraints are optional; not specifying a constraint on a parameter is equivalent to using a Object constraint.
What Does Template Mean? A template is a C++ programming feature that permits function and class operations with generic types, which allows functionality with different data types without rewriting entire code blocks for each type.
Let's define a few concepts in this post. A concept can be defined by a function template or by a variable template. A variable template is new with C++14 and declares a family of variables. If you use a function template for your concept, it's called a function concept; in the second case a variable concept.
This isn't a specialization, you actually redeclared the primary template, which is indeed an error.
A specialization would look like this:
template<typename T>
class X { };
template<AorB T>
class X<T> { };
// ^^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With