2017-01-20 1 views
0

Using code adapted from this answer、私は<in>という名前の演算子を採用しました。これは、コンパイラのエラーです:Koenigルックアップと "C++はすべての宣言に型指定子を必要とします"

/../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を使用してコンパイルされます。

+2

'in_t'はこのコンテキストでは型ではありません。フォワードは 'struct in_t;'を宣言してから使用します。タイプは、使用する前に宣言する必要があります。 –

+0

re llim:複数のガイドが、名前空間にコードをインデントしないようにとアドバイスしました。 –

+0

コードが壊れています。型を宣言して関数のパラメータとして使用する必要があります。 – Peter

答えて

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.

関連する問題