我在 Sun Studio 中为模板类提供模板朋友时遇到问题。该代码可以使用 GNU G++(4.4.1 和 4.4.3)正常编译,但使用 Sun Studio C++(5.9 SunOS_sparc 补丁 124863-01 2007/07/25)失败。
这是一个最小的例子:
// Forward declarations
template<class T> class M;
template<class T> void f(M<T>, M<T>);
// Define M<T>
template<class T>
class M
{
public:
void f(M<T>) { }
friend void ::f<>(M<T>, M<T>);
};
// Define global function f
template<class T>
void f(M<T> a, M<T> b)
{
a.f(b);
}
M<int> a;
当我尝试通过 编译它时CC -c -o t3.o t3.cpp
,我收到以下错误消息:
"t3.cpp", line 12: Warning: A friend function with template-id name must have a template declaration in the nearest namespace.
"t3.cpp", line 22: Where: While specializing "M<int>".
"t3.cpp", line 22: Where: Specialized in non-template code.
"t3.cpp", line 12: Error: Global scope has no declaration for "f".
"t3.cpp", line 22: Where: While specializing "M<int>".
"t3.cpp", line 22: Where: Specialized in non-template code.
1 Error(s) and 1 Warning(s) detected.
这是 Sun Studio C++ 的问题,还是无效的 C++(仍然被 GCC 接受并且没有给出警告-Wall -pedantic
)?有没有一种优雅的方法来更改代码,使其符合标准并在 GCC 和 Sun Studio 下编译?
提前非常感谢!