【发布时间】:2015-01-21 20:19:26
【问题描述】:
只是测试/学习在 C++ 中编写管道,重载 | 运算符,以下程序
编译失败:
二进制表达式候选模板的无效操作数被忽略: ... 无法将 'bitset' 与 'vector' 匹配
似乎编译器正在尝试使用标准 |定义。 该代码适用于显式调用和显式类型参数集。
// g++ -std=c++11 Pipeline.cpp
#include <iostream>
#include <vector>
// ..............................................................
// ..............................................................
std::string dup (std::string s) {
return s + s;
}
// ..............................................................
// ..............................................................
template <typename TI, typename TO>
std::vector<TO> operator | (const std::vector<TI> & in, std::function<TO(TI)> f) {
std::vector<TO> out;
for (auto i : in) {
out.push_back ( f(i) );
}
return out;
}
// ..............................................................
// ..............................................................
int main () {
std::cout << " hello " << std::endl;
std::vector<std::string> vs = {"one", "two", "three", "four", "five"};
auto res = vs | dup;
// OK: vector<string> res = operator|<string,string> (vs, dup);
for (auto s : res) { std::cout << s << std::endl; }
} // ()
完整的错误信息:
Pipeline.cpp:29:17: error: invalid operands to binary expression
('std::vector<std::string>' and 'std::string (*)(std::string)')
auto res = vs | dup;
~~ ^ ~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/bitset:1045:1: note:
candidate template ignored: could not match 'bitset' against 'vector'
operator|(const bitset<_Size>& __x, const bitset<_Size>& __y) _NOEXCEPT
^
Pipeline.cpp:13:17: note: candidate template ignored: could not match
'function<type-parameter-0-1 (type-parameter-0-0)>' against
'std::__1::basic_string<char> (*)(std::__1::basic_string<char>)'
std::vector<TO> operator | (const std::vector<TI> & in, std::function<TO...
^
1 error generated.
【问题讨论】:
-
这是完整的错误输出吗?为什么它抱怨
bitset,因为显示的源代码中没有位集? -
@JoachimPileborg 我刚刚附上了完整的错误信息。
-
问题出在模板函数中。如果你用
std::string替换template就可以了。 -
函数指针不是
std::function,所以模板参数推导会失败。