编译器不创建模板化ostream<<运算符 [英] Compiler not creating templated ostream << operator

查看:181
本文介绍了编译器不创建模板化ostream<<运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,在头中定义为:

I have a class, defined in a head as:

template <typename T> class MyClass
{
   template <typename U> friend std::ostream& operator<<(std::ostream& output, const MyClass<U>& p);
   public:
      ...
}

文件,我有:

template <typename U> std::ostream& operator<<(std::ostream& output, const MyClass<U>& m)
{
   output << "Some stuff";
   return output;
}

但是,当我尝试并使用这个运算符(即std :: cout << MyClass()),我得到以下链接器错误:

Which all looks fairly kosher. However, when I try and use this operator (i.e. std::cout << MyClass()), I get the following linker error:

Undefined symbols: std::basic_ostream<char, std::char_traits<char> >& operator<< <InnerType>(std::basic_ostream<char, std::char_traits<char> >&, MyClass<InnerType> const&)

我很惊讶编译器没有为我自动生成这个...对于我做错了什么建议?

I am suprised the compiler hasn't automagicially generated this for me... Any suggestions as to what I'm doing wrong?

推荐答案


在实现文件中,我有:

In an implementation file, I have:

那就是问题所在。不能在头文件和实现文件之间拆分模板定义。由于模板的性质,C ++编译器在这里很有趣。

That's the problem. You can't split template definitions between header and implementation files. Due to the nature of templates, C++ compilers are finicky here. Define all the code in the header to make it work.

事实上,这里的问题是所有的模板定义都必须在同一个编译单元中,因为C ++标准不支持不能定义模板信息如何在不同单元之间共享。这些单元由链接器拼接在一起,但泛型在编译时(这是较早的),在链接时不是解析。

In fact, the problem here is that all template definitions must reside within the same compilation unit because the C++ standard doesn't define how template information are shared across different units. These units are stitched together by the linker, but generics are resolved at compile time (which is earlier), not at link time.

理论上,C ++标准定义了一个关键字 export 来处理这些情况。在实践中,没有编译器实现这一点(有一个例外?),并且没有意图改变这一点,因为成本/有用性权衡被认为不够好。

Theoretically, the C++ standard defines a keyword, export, to handle these cases. In practice, no compiler implements this (with one exception?), and there is no intention to change this because the cost/usefulness trade-off is not considered good enough.

这篇关于编译器不创建模板化ostream&lt;&lt;运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆