Python "in" imitation in c ++

I was able to determine the exact syntax, like in python (checking for a value in a container), so you can just check if the value is in any container that supports the begin()/ methods end().

Here is my implementation:

#include <algorithm>
#include <iostream>
#include <vector>

template<class T>
struct specified {
    specified(T const& value) : value_(value) {}
    T value_;

    template<class Container>
    bool operator * (Container const& cont) {
        return (std::find(cont.begin(), cont.end(), value_) != cont.end());
    }

};

struct general {
    template<class T>
    friend specified<T> operator *(T const& rhs, general const&) {
        return specified<T>(rhs);
    }
};

#define in * general() *

int main() {
    std::vector<int> vec{1,2,3};
    std::cout << 1 in vec << std::endl;
    std::cout << 4 in vec << std::endl;
}

Live on coliru

My question is, does he have any pitfalls? It is safe?

EDIT:

String literal support

+4
source share
2 answers

It has a small workaround for strings.

Doesn't work with string literals.

std::vector<string> vec{"1","2","3"};
std::cout << "1" in vec << std::endl;
std::cout << "4" in vec << std::endl;

This code leads to a compile-time error.

error: array used as initializer
  specified(T const& value) : value_(value) {}

++ char[] , string. .

std::cout << string("1") in vec << std::endl;
+2

, , #define.

void foo(int in) { }

, . , .

, , - . , , ,

 std::find(cont.begin(), cont.end(), value_) != cont.end()

, ,

value_ in cont

, , .

+1

Source: https://habr.com/ru/post/1673201/


All Articles