Waivio

Recommended Posts

Beispiel eines Konzeptes in c++20

5 comments

ozelot471.2 Klast yearPeakD2 min read

In diesem Code wird ein kleines Anwendungsbeispiel gezeigt, wie man die Konzepte aus c++ verwenden kann. Die Klasse Point2D muss die Voraussetzungen der Konzepte erfüllen, um auf diese Angewendet werden zu können. Würde zum Beispiel die Funkton size() in Point2D fehlen, so gäbe es ein Compilerfehler.

#include <iostream>
#include <concepts>
#include <type_traits>
#include <vector>

// define the type of scalar
template<typename T>
using Skalar = std::decay<decltype(T()[0])>::type;

// restrict the IntVector
template<typename T>
concept IntVector = std::integral<Skalar<T>> && requires(T t) {{ t.size()} -> std::integral;};

template<typename T>
auto product(const T& t) -> Skalar<T> {
    Skalar<T> result = 0;
    for(std::size_t n = 0; n < t.size(); n++){
        result += t[n] * t[n];
    }
    return result;
}

// Custom class to test the matching for above concept with requirement
class Point2D {
public:
    float x;
    float y;

    // custom size function to match the above IntVector concept requirement
    auto size() const -> unsigned int {
        return 2;
    }

    // access x or y
    auto operator[](int n) const -> float {
        return n == 0 ? x : y;
    }
};

int main(){
    // using a vector with has it's own size function
    std::vector<int> a = {1, 2, 3, 4, 5};
    std::cout << product(a) << '\n';

    // using our custom class
    Point2D b = {2, 3};
    std::cout << product(b) << '\n';
}

https://img.blurt.world/blurtimage/ozelot47/335617cf1a48a7ed756dc9dd4c3da61b434715c8.png

Comments

Sort byBest
AI
Waivio AI Assistant
How can I help you today?