Koenig查找和" C ++需要所有声明的类型说明符"

时间:2017-01-20 21:41:18

标签: c++ compiler-errors operators

Using code adapted from this answer,我改编了一个名为<in>的运营商。这是编译器错误:

/../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);

应该像:

一样使用
if (item <in> vec) {
    // ...
}

我不认为我的代码被破坏了,所以我可能会问他们一个问题。但这不是重点。

#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);
}

使用g++ ti.cpp -O3 --std=c++11 -o time编译。

1 个答案:

答案 0 :(得分:2)

您有几个错误:

前方声明的错误顺序:

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

糟糕的运营商:

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));
}

但一旦修复,它就有效。 Demo.