【发布时间】:2017-06-05 23:33:47
【问题描述】:
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编译。
【问题讨论】:
-
in_t不是此上下文中的类型。在使用之前转发声明struct in_t;。类型必须在使用前声明。 -
re llim:一些指南建议我不要在命名空间中缩进代码。
-
您的代码已损坏。在将其用作函数的参数之前,必须先声明一个类型。
-
@Peter 已添加,同样的错误。
-
@FrançoisAndrieux 见上面的评论。
标签: c++ compiler-errors operators