2017-01-20 44 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

重新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.