How to make the name of a type predicate available for a template?

Viewed 67

I have just started to learn C++'s templates using Bjarne Stroustrup's "Programming Principles and Practice Using C++" (second edition). In chapter 19.3.3, during the process of implementing a vector, the writers introduce the concept of concept as follows:

... We call a set of requirements on a template argument a concept ... In C++14, we can make that explicit:

template<typename T>        // for all types T
    requires Element<T>()   // such that T is an Element
class vector {
        //...
};

This shows that a concept is really a type predicate, that is, a compile-time-evaluated (constexpr) function that returns true if the type argument (here, T) has the properties required by the concept (here, Element) and false if it does not.

In another book written by Bjarne Stroustrup ("A Tour of C++", second edition, chapter 6.2.1), the writer gives a similar example:

template<Element T>
class Vector {
private:
    T* elem;    // elem points to an array of sz elements of type T
    int sz;
    //...
};

However, this time the writer states:

... C++ does not officially support concepts before C++20 ...

I tried to run above code (in Visual Studio 2022 using C++20) but it seems that the identifier Element is undefined (C2061). I wonder if Element (and many other concepts stated by Stroustrup in the books) is defined in the standard library? How could we make the name available to use?

1 Answers

I tried to run above code (in Visual Studio 2022 using C++20) but it seems that the identifier Element is undefined

I think you misunderstood what was being said. In particular, the author was trying to explain the concept of "concepts"(by giving an example) that uses some predefined Element.

You're getting the error because your program does not have any such construct called Element. That is, to use Element<T>() you must first declare that there is one such thing called Element.

Related