我的代码出了什么问题?
template<int E, int F>
class Float
{
friend Float<E, F> operator+ (const Float<E, F> &lhs, const Float<E, F> &rhs);
};
Run Code Online (Sandbox Code Playgroud)
G ++只是警告:
float.h:7: warning: friend declaration ‘Float<E, F> operator+(const Float<E, F>&, const Float<E, F>&)’ declares a non-template function
float.h:7: warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning
我试着add <> after the function name here在警告说明中提到,但是g ++给了我一个错误.
我用clang …
声明模板函数的朋友涉及一些令人难以置信的不直观的语法,即使对于C++!选择额外<>需要的语法背后的理由是什么?使用template关键字不是更合理吗?
对于那些不了解这一点的人,这里有一个你可能尝试做的例子:
template <typename T>
class Foo
{
int x;
friend void bar(Foo<T>);
};
template <typename T>
void bar(Foo<T> f)
{
std::cout << f.x;
}
Run Code Online (Sandbox Code Playgroud)
如果您尝试调用bar(Foo<T>()),则会出现链接器错误.
要解决这个问题,你必须转发声明bar(因此Foo),然后<>在朋友声明中粘贴一个奇怪的位置.
template <typename T> class Foo;
template <typename T> void bar(Foo<T>);
template <typename T>
class Foo
{
int x;
friend void bar<>(Foo<T>); // note the <> (!?)
};
template <typename T>
void bar(Foo<T> f)
{
std::cout << f.x;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,<>语法背后的基本原理是什么?使用 …