g++ 显示一个奇怪的编译错误 。
上面写着“ std::plus is not a 函数
” for the follow code, 尽管我并不包括 lt; 功能 & gt;
和不使用发生错误的
。
这是代码:
#include <iostream>
template<class T1, class T2, class T3>
struct MyStruct {
T1 t1; T2 t2; T3 t3;
MyStruct() {}
MyStruct(T1 const& t1_, T2 const& t2_, T3 const& t3_)
: t1(t1_), t2(t2_), t3(t3_) {}
};
template<class T1, class T2, class T3>
MyStruct<T1, T2, T3> plus(MyStruct<T1, T2, T3> const& x,
MyStruct<T1, T2, T3> const& y) {
// ...
}
int main() {
typedef MyStruct<int, double, std::string> Struct;
Struct x(2, 5.6, "bar");
Struct y(6, 4.1, "foo");
Struct result = plus(x, y);
}
这是全部错误( 略微重写) :
/usr/include/c++/4.2.1/bits/stl_function.h: In function int main() :
/usr/include/c++/4.2.1/bits/stl_function.h:134:
error: template<class _Tp> struct std::plus is not a function,
plus3.cc:13: error:
conflict with template<class T1, class T2, class T3>
MyStruct<T1, T2, T3> plus(const MyStruct<T1, T2, T3>&,
const MyStruct<T1, T2, T3>&)
plus3.cc:21: error: in call to plus
有谁知道这是为什么, 以及如何避免错误? 我真的想调用该函数 plus
。
我的 plus
函数没有3个模板参数时,就不会发生错误。 查看 std:: plus
的定义后, 3个模板参数是有道理的 :
template <class _Tp>
struct plus : public binary_function<_Tp, _Tp, _Tp>
但还是很奇怪, 因为std::+
当时甚至不知道。
<强 > UPATE: 强 >
针对某些答案, 我会粘贴略微修改的代码, 并给出错误 。 我的 < code> plus code> 函数在 < code> namespace foo code> 中在此, 它被调用同一命名空间, 所以不需要使用 < code> foo: code> 来限定它 : < / code> :
#include <string>
namespace foo {
template<class T1, class T2, class T3>
struct MyStruct {
T1 t1; T2 t2; T3 t3;
MyStruct() {}
MyStruct(T1 const& t1_, T2 const& t2_, T3 const& t3_)
: t1(t1_), t2(t2_), t3(t3_) {}
};
template<class T1, class T2, class T3>
MyStruct<T1, T2, T3> plus(MyStruct<T1, T2, T3> const& x,
MyStruct<T1, T2, T3> const& y) {
// ...
}
template<class T1, class T2, class T3>
MyStruct<T1, T2, T3> bar(MyStruct<T1, T2, T3> const& x,
MyStruct<T1, T2, T3> const& y) {
return plus(x, y);
}
} // end foo
int main() {
typedef foo::MyStruct<int, double, std::string> Struct;
Struct x(2, 5.6, "bar");
Struct y(6, 4.1, "foo");
Struct result = foo::bar(x, y);
}