只是测试/学习用 C++ 重载 |
运算符编写管道,以下程序
编译失败:
invalid operands to binary expression candidate template ignored: ... could not match 'bitset' against '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.
最佳答案
模板参数推导不会查看隐式转换。函数指针不是 std::function
,因此编译器无法推断出哪些模板参数来实例化您的 operator|
和。一般来说,std::function<...>
, 其中...
包含模板参数,不是接受任意函数或函数对象的正确方法。
取而代之的是,为仿函数接受任何类型:
template <typename TI, typename F>
/* something */ operator | (const std::vector<TI> & in, F f)
然后找出返回类型。
返回类型是 std::vector
,其值类型是通过调用 f
返回的类型在 in
的一个元素上- 换句话说,decltype(f(in[0]))
.然而,f
可以返回一个引用类型,并且在这些情况下您确实希望 vector 的值类型是所引用的类型。使用 std::decay
(或 std::remove_reference
)去除任何引用性:
template <typename TI, typename F>
auto operator | (const std::vector<TI> & in, F f) -> std::vector<typename std::decay<decltype(f(in[0]))>::type> {
std::vector<typename std::decay<decltype(f(in[0]))>::type> out;
/*...*/
}
Demo .
关于c++ - 重载运算符中的类型不匹配(编写管道),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28048474/