C++ Logo

std-proposals

Advanced search

Re: [std-proposals] c++ interfaces vs templates

From: Pavel Vazharov <freakpv_at_[hidden]>
Date: Thu, 8 Dec 2022 18:36:18 +0200
> Has anyone proposed something like this?
>
> ---
> interface sizeable {
> size_t size() cost;
> }
>
> bool too_big(sizeable thing) {
> return thing.size() > 100;
> }
>
> void main() {
> std::cout << too_big(string("sdfkjhsdfjh")) << std::endl;
> std::cout << too_big(vector<int>(1000,0)) << std::endl;
> }
>

Looks like the concepts introduced in C++20 -
https://godbolt.org/z/q7ra1G6G5

#include <concepts>
#include <iostream>
#include <utility>
#include <vector>

template<typename T>
concept sizeable = requires(T v)
{
    { std::as_const(v).size() } -> std::convertible_to<std::size_t>;
};

bool too_big(const sizeable auto& thing) {
      return thing.size() > 100;
}

int main(int, const char**)
{
    //std::cout << too_big("adfasdfsa") << '\n';
    std::cout << too_big(std::vector<int>{1,2,3,4}) << '\n';

    return 0;
}

Received on 2022-12-08 16:36:31