模板错误代码块,C++,代码块,错误

template error codeblocks,c++, codeblocks, error

本文关键字:代码 错误 C++ 错误代码      更新时间:2023-10-16

我想编译:

#include<iostream>
#include"gettype.*"
using namespace std;

int main() { 
int i;
cout << getType(i) << endl; 
unsigned int ui;
cout << getType(ui) << endl; 
char c;
cout << getType(c) << endl; 
double d;
cout << getType(d) << endl;
bool b;
cout << getType(b) << endl; 
float f;
cout << getType(f) << endl; 
}

将此作为模板:

#ifndef GETTYPE_T
#define GETTYPE_T
template <typename T>
std::string getType(T t) { return "unbekannter Typ";}
template<typename T> std::string getType(int t) { return "int";}
template<typename T> std::string getType(unsigned int t) { return "unsigned                  int";}
template<typename T> std::string getType(double t) { return "double";}
template<typename T> std::string getType(char t) { return "char";}
template<typename T> std::string getType(bool t) { return "bool";}
#endif

我从代码块中的控制台收到此错误:

||=== Build: Debug in gettype.t (compiler: GNU GCC Compiler) ===|
gettype.t.c|6|error: expected '=', ',', ';', 'asm' or '__attribute__' before     '<' token|
gettype.t.c|9|error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token|
gettype.t.c|10|error: expected '=', ',', ';', 'asm' or '__attribute__'        before '<' token|
gettype.t.c|11|error: expected '=', ',', ';', 'asm' or '__attribute__'    before '<' token|
gettype.t.c|12|error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token|
gettype.t.c|13|error: expected '=', ',', ';', 'asm' or '__attribute__'  before '<' token|
||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

我不知道这里有什么问题...:-(提前感谢你的时间:-)干杯。

你不需要

"专门化"函数的模板化版本,你只需要重载,而不需要对已知类型进行template<typename T>

std::string getType(int t) { return "int";}
std::string getType(bool t) { return "bool";}

等等。这些将使模板化版本过载。

你写过:

#include "gettype.*"

错误消息告诉您 GCC 包含一个名为 gettype.t.c 的文件,并尝试将其编译为 C 文件。

我不知道你想做什么,但是如果你修复你的包含,所以它只包含gettype.t而不gettype.*它会起作用(为什么你的标题有一个.t扩展名?