我现在已经在StackOverflow.com上阅读了几个关于我的问题的问题,但似乎没有一个能解决我的问题.或者我可能做错了... <<如果我将其转换为内联函数,则重载会起作用.但是我如何让它在我的情况下工作?
warning: friend declaration std::ostream& operator<<(std::ostream&, const D<classT>&)' declares a non-template function
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
/tmp/cc6VTWdv.o:uppgift4.cc:(.text+0x180): undefined reference to operator<<(std::basic_ostream<char, std::char_traits<char> >&, D<int> const&)' collect2: ld returned 1 exit status
代码:
template <class T>
T my_max(T a, T b)
{
if(a > b)
return a;
else
return b;
}
template <class classT> …Run Code Online (Sandbox Code Playgroud) 我有一个基类类似于下面的代码.我试图重载<<以与cout一起使用.但是,g ++说:
base.h:24: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, Base<T>*)’ declares a non-template function
base.h:24: 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
Run Code Online (Sandbox Code Playgroud)
我尝试在类声明/原型中添加<<之后的<>.但是,我明白了does not match any template declaration.我一直试图让操作符定义完全模板化(我想要的),但我只能使用以下代码使用操作符手动实例化.
base.h
template <typename T>
class Base {
public:
friend ostream& operator << (ostream &out, Base<T> *e);
};
Run Code Online (Sandbox Code Playgroud)
base.cpp
ostream& operator<< (ostream &out, Base<int> *e) {
out << e->data;
return …Run Code Online (Sandbox Code Playgroud) 所以我这里有一些使用 gcc、clang 和 msvc 编译的代码:
#include <cstdio>
#include <type_traits>
struct c_class;
template <class T> struct holder { friend auto adl_lookup(holder<T>); };
template <class C, class T> struct lookup {
friend auto adl_lookup(holder<T>) { return holder<C>{}; }
};
struct cpp_class : lookup<cpp_class, c_class *> {
cpp_class() {}
};
int main() {
static_assert(std::is_same<holder<cpp_class>,
decltype(adl_lookup(holder<c_class *>{}))>{},
"Failed");
}
Run Code Online (Sandbox Code Playgroud)
之所以在类adl_lookup中定义lookup而不是在类中定义,是为了在继承CRTP类时holder可以从c_class到进行“反向”查找。所以友元函数不能移到类中。cpp_classlookup<cpp_class, c_class *>holder
但是,在 gcc 上,我收到有关非模板友元函数的警告:
<source>:9:37: warning: friend declaration 'auto adl_lookup(holder<T>)' declares a …Run Code Online (Sandbox Code Playgroud)