Konzepte in c++20

Seit der Einführung des c++20 Standards gibt es unter anderem die sogenannten Konzepte (concepts). Mit Konzepte ist es möglich den generischen Typen eines Templates zu beschränken. Oder man formuliert eine Anforderung die Erfüllt werden muss, um ein Template verwenden zu können.

Außerdem sorgt die Verwendung von Konzepte ,dass der Compiler eine entsprechende Fehlermeldung ausgibt, falls nicht unterstütze Typen bzw. die Anforderungen nicht erfüllt werden.

#include <iostream>
#include <concepts>

// Restrict a type which must have a multithread function
template<typename T>
concept is_multithreadable = requires(T value) { value.multithread();};

// Restrict another type which must have a multithread function AND a print function
template<typename T>
concept is_printable = is_multithreadable<T> && requires(T value) { value.print();};

class OnlyMultiThread {
public:
    void multithread();
};

class MultiThreadPrint {
public:
    void set();
    void print();
    void multithread();
};

void only_multithread(is_multithreadable auto){
    std::cout << "only multithread without print" << '\n';
}
void multi_print(is_printable auto){
    std::cout << "multithread and print" << '\n';
}

int main(){
    // OK. OnlyMultiThread has a multithread function
    only_multithread(OnlyMultiThread());
    // OK. MultiThreadPrint has both functions. But for this conecpt, only multithread is required and print is optional but not required.
    only_multithread(MultiThreadPrint());
    // Error. OnlyMultiThread has no print function. Violation of the concept
    multi_print(OnlyMultiThread());
    // OK. MultiThreadPrint has both functions.
    multi_print(MultiThreadPrint());
    // Error. std::string has no multithread function. Violation of the concept
    only_multithread(std::string);
}



0
0
0.000
2 comments