gpt4 book ai didi

c++ - cpp 文件的函数模板特化语法

转载 作者:太空狗 更新时间:2023-10-29 20:33:45 27 4
gpt4 key购买 nike

我有一个在我的 .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文章使用我的第一个版本。

最佳答案

正确的语法取决于您实际要执行的操作。添加 <>不仅仅是修复 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<uint8_t> 的人不会实例化您已经定义的主模板,而是寻找专门的定义。这看起来不像是您想要做的,但如果是,您实际上必须在某个时候定义这些特化。

关于c++ - cpp 文件的函数模板特化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53306863/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com