0

Using code adapted from this answer, I adapted an <in> named operator. This is the compiler error:

/../ti.cpp:6:31: error: C++ requires a type specifier for all declarations
bool named_invoke(E const &e, in_t, C const &container);
                              ^
/../ti.cpp:45:16: error: invalid operands to binary expression ('int' and 'operators::in_t')
    cout << (1 <in> vec);

It should be used like:

if (item <in> vec) {
    // ...
}

I don't think it is my code that is broken, so I may be asking a question for them. But that's beside the point.

#include <iostream>
#include <vector>

namespace operators {  // forward declare operators
    template<class E, class C>
    bool named_invoke(E const &e, in_t, C const &container);
    struct in_t;
}  // namespace operators


namespace named_operator {
    template<class D>
    struct make_operator { make_operator() {}};

    template<class T, char, class O>
    struct half_apply { T &&lhs; };

    template<class Lhs, class Op>
    half_apply<Lhs, '<', Op> operator*(Lhs &&lhs, make_operator<Op>) {
        return {std::forward<Lhs>(lhs)};
    }

    template<class Lhs, class Op, class Rhs>
    auto operator*(half_apply<Lhs, '>', Op> &&lhs, Rhs &&rhs)
    -> decltype(operators::named_invoke(std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs))) {
        return operators::named_invoke(std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs));
    }
}  // namespace named_operator


namespace operators {
    struct in_t: named_operator::make_operator<in_t> {};
    in_t in;

    template<class E, class C>
    bool named_invoke(E const &e, in_t, C const &container) {
        using std::begin; using std::end;
        return std::find(begin(container), end(container), e) != end(container);
    }
}  // operators


using operators::in;
using namespace std;


int main() {
    // test it
    vector<int> vec = {1};
    cout << (1 <in> vec);
}

Compiled using g++ ti.cpp -O3 --std=c++11 -o time.

Community
  • 1
  • 1
noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67

1 Answers1

2

You have several errors:

Bad order of forward declaration:

namespace operators {  // forward declare operators
    struct in_t;

    template<class E, class C>
    bool named_invoke(E const &e, in_t, C const &container);
}  // namespace operators

Bad operators:

template<class Lhs, class Op>
half_apply<Lhs, '<', Op> operator<(Lhs &&lhs, make_operator<Op>) {
    return {std::forward<Lhs>(lhs)};
}

template<class Lhs, class Op, class Rhs>
auto operator>(half_apply<Lhs, '<', Op> &&lhs, Rhs &&rhs)
-> decltype(operators::named_invoke(std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs))) {
    return operators::named_invoke(std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs));
}

but once fixed, it works. Demo.

noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67
Jarod42
  • 203,559
  • 14
  • 181
  • 302