提问人:Gregor Hartl Watters 提问时间:11/10/2023 更新时间:11/10/2023 访问量:44
由于嵌套在模板化类中的类内的“<<”重载而导致链接错误 [duplicate]
Linking error due to `<<` overload inside class nested within templated class [duplicate]
问:
我正在尝试重载流插入运算符以允许将我的类的实例打印到 .<<
gml::tensor<T>::shape
stdout
为了重现问题的根源,我尽可能地减少了我的代码:
#include <iostream>
#include <concepts>
namespace gml {
template <typename T>
concept Numeric = requires (T value) {
T{1};
};
template <Numeric T>
class tensor;
template <Numeric T>
std::ostream &operator<<(std::ostream&, const typename tensor<T>::shape&);
template <Numeric T>
class tensor {
public:
class shape {
public:
shape() = default;
friend std::ostream &operator<<(std::ostream&, const shape&);
};
tensor() {
std::cout << "tensor ctor" << std::endl;
}
};
template <Numeric T>
std::ostream &operator<<(std::ostream &out, const typename tensor<T>::shape &s) {
return out << "PRINTING AT LAST!!!\n" << std::endl;
}
}
int main() {
gml::tensor<long double>::shape s;
std::cout << s << std::endl;
return 0;
}
我得到的链接器错误是:
Undefined symbols for architecture arm64:
"gml::operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, gml::tensor<long double>::shape const&)", referenced from:
_main in test-eaec7e.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我开始认为我想做的事情是不可能的。
我可以将重载定义为成员函数,但在此之前,我想知道是否可以执行任何操作来允许在 之外定义该函数。<<
gml::tensor<T>::shape
注意:删除 和 forward 声明没有任何区别。tensor
operator<<
答: 暂无答案
上一个:静态元素和成员元素的编译错误
评论
friend
operator<<
operator<<
friend
friend
friend
operator<<
gml::tensor<T>::shape
template <Numeric T> friend std::ostream &operator<<(std::ostream&, const typename tensor<T>::shape&);