C++模板上下文中的特化和实例化有什么区别.从我到目前为止所读到的内容,以下是我对专业化和实例化的理解.
template <typename T>
struct Struct
{
T x;
};
template<>
struct Struct <int> //specialization
{
//code
};
int main()
{
Struct <int> s; //specialized version comes into play
Struct <float> r; // Struct <float> is instantiated by the compiler as shown below
}
Run Code Online (Sandbox Code Playgroud)
Struct <float>由编译器实例化
template <typename T=float>
struct Struct
{
float x;
}
Run Code Online (Sandbox Code Playgroud)
我对模板实例化和专业化的理解是否正确?
我想知道是否可以使用gdb print命令来评估c ++模板函数的结果.在以下带有简单id函数的代码中,我尝试了print结果id(x),但它似乎id或id<t>从未存在过.我使用的代码如下,编译时使用g++ -std=c++11 -g test7.cpp:
template<typename T>
T id(T x) {return x;}
int main() {
int i = 0;
i = i + 1;
}
Run Code Online (Sandbox Code Playgroud)
在GDB中,我尝试print如下:
Breakpoint 1, main () at test7.cpp:6
6 i = i + 1;
(gdb) print i
$1 = 0
(gdb) print id(i)
No symbol "id" in current context.
(gdb) print id<int>(i)
No symbol "id<int>" in current context.
Run Code Online (Sandbox Code Playgroud)
如你所见,我总是得到"没有符号ID".
有一篇关于 …
我知道具有不同数据类型的C++模板允许函数共享类似的实现代码,但我想知道如果函数具有完全不同的执行路径,取决于数据类型.反正有没有这样做?
我有一个模板化的函数在我的.h中声明并在我的.cpp中实现:
//file.h
class FileReader{
template <class T> void Read( T *aValue );
};
//file.cpp
template<class T>
void
FileReader::Read( T *aValue )
{
//implementation
}
Run Code Online (Sandbox Code Playgroud)
为了允许在我的.cpp中实现,我有
template void FileReader::Read<uint8_t>( uint8_t * );
template void FileReader::Read<uint16_t>( uint16_t * );
Run Code Online (Sandbox Code Playgroud)
但是试图修复一个doxygen问题,有人在这里指出我应该使用
template<> void FileReader::Read<uint8_t>( uint8_t * );
template<> void FileReader::Read<uint16_t>( uint16_t * );
Run Code Online (Sandbox Code Playgroud)
这确实解决了doxygen问题,但它在链接时打破了我的编译.
=>在我的.cpp中专门化我的函数模板并允许函数链接的正确语法是什么?
有没有办法在if语句中测试参数的数据类型?这是一个源代码示例:它不会编译,但它用于表达我的意图.
typedef char cInt[sizeof(int)];
typedef char cFloat[sizeof(float)];
typedef char cDouble[sizeof(double)];
template<typename T>
char* convertToCharStr( const T& t ) {
if ( t == int ) {
cInt c = t;
return c;
}
if ( t == float ) {
cFloat c = t;
return c;
}
if ( t == double ) {
cDouble c = t;
return c;
}
return nullptr;
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我正在尝试创建一个模板函数,它可以采用任何默认数据类型,如int,unsigned int,float,double,并根据数据类型,它将在堆栈上创建相应的char []变量.传入的数据类型并将数据存储到char []并将指针返回函数.
我会把它放在它的上面,但作为一个注释,字符数组应该是unsigned char.