Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class template specialization with constraint / concept

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.

like image 535
wimalopaan Avatar asked May 18 '17 10:05

wimalopaan


People also ask

What is meant by template specialization?

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.

What is constraints in C++ with example?

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 in C++?

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.

How do you declare a concept in C++?

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.


1 Answers

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> { };
//     ^^^
like image 194
Quentin Avatar answered Sep 20 '22 08:09

Quentin