【问题标题】:function template specialization syntax for cpp filecpp 文件的函数模板特化语法
【发布时间】:2018-11-14 18:45:25
【问题描述】:

我在我的 .h 中声明了一个模板化函数并在我的 .cpp 中实现:

//file.h
class FileReader{
template <class T> void Read( T *aValue );
};

//file.cpp
template<class T>
void
FileReader::Read( T *aValue )
{
    //implementation
}

为了允许在我的 .cpp 中实现,我有

template void FileReader::Read<uint8_t>( uint8_t * );
template void FileReader::Read<uint16_t>( uint16_t * );

但是试图解决一个 doxygen 问题,有人指出我应该使用 here

template<> void FileReader::Read<uint8_t>( uint8_t * );
template<> void FileReader::Read<uint16_t>( uint16_t * );

这确实解决了 doxygen 问题,但它在链接时破坏了我的编译。

=>在我的 .cpp 中专门化我的函数模板并允许链接函数的正确语法是什么?

This 其他问题似乎表明我应该使用我的第二个版本。但是this的文章使用的是我的第一个版本。

【问题讨论】:

  • @user463035818 我重新打开了这个问题,因为 OP 正确地尝试为一组特定的模板参数显式实例化类模板,但被误导了
  • @PiotrSkotnicki 谢谢。看了cpp和一些tempalte的东西,没仔细看

标签: c++ templates


【解决方案1】:

正确的语法取决于您实际尝试执行的操作。添加&lt;&gt; 不仅仅是修复 Doxygen 的一种方法——它大大改变了程序的含义!

以下是显式实例化定义

template void FileReader::Read<uint8_t>( uint8_t * );
template void FileReader::Read<uint16_t>( uint16_t * );

它们告诉编译器立即实例化函数模板,并为实例化发出符号,以便它们可以被另一个翻译单元链接到。这似乎是你真正想要做的。

以下是显式特化声明

template<> void FileReader::Read<uint8_t>( uint8_t * );
template<> void FileReader::Read<uint16_t>( uint16_t * );

它们告诉编译器你将为那些特定的模板参数定义你自己的模板特化。因此,任何尝试调用FileReader::Read&lt;uint8_t&gt; 的人都不会实例化您已经定义的主模板,而是寻找专门的定义。看起来这不是您想要做的事情,但如果是这样,您实际上必须在某个时候定义这些专业化。

【讨论】:

  • 感谢您的澄清!现在我需要修复我的 doxygen
  • 下一篇:C++ 语法令人困惑的本质。
猜你喜欢
  • 2022-06-18
  • 2016-08-05
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
相关资源
最近更新 更多