C++ 这是什么<&燃气轮机&引用;是指在模板类函数中?
有这样一个代码C++ 这是什么<&燃气轮机&引用;是指在模板类函数中?,c++,templates,C++,Templates,有这样一个代码 const std::string DeviceTypeStrings[] ={ "A", "B", "C", "D", "E" }; enum DeviceTypes { A = 0, B, C, D, E }; template <DeviceTypes T> class DeviceType; template <DeviceTypes T> std::ostream& operator<< (std::ostream&
const std::string DeviceTypeStrings[] ={ "A", "B", "C", "D", "E" };
enum DeviceTypes { A = 0, B, C, D, E };
template <DeviceTypes T> class DeviceType;
template <DeviceTypes T> std::ostream& operator<< (std::ostream& output, const DeviceType<T>& dev);
template <DeviceTypes T> class DeviceType {
public:
static const int value = T;
static const std::string string;
friend std::ostream & operator<< <>(std::ostream & output, const DeviceType<T> & deviceType );
};
template <DeviceTypes T> const std::string DeviceType<T>::string = DeviceTypeStrings[T];
template <DeviceTypes T> std::ostream & operator<< (std::ostream & output, const DeviceType<T> & deviceType ){
if ( DeviceType<T>::string.find(' ') != std::string::npos ){
return output << "\"" << DeviceType<T>::string << "\"";
} else {
return output << DeviceType<T>::string;
}
}
int main () {
DeviceType<A> myType;
std::cout << myType << std::endl;
return 0;
}
const std::string设备类型字符串[]={“A”、“B”、“C”、“D”、“E”};
枚举设备类型{A=0,B,C,D,E};
模板类设备类型;
template std::ostream&operator编译器检查它只是意味着友元声明引用了函数templateoperator的特定专门化,与此相同。
请参阅“模板专门化”一章
//模板专门化
#包括
使用名称空间std;
//类模板:
模板
类霉菌容器{
T元素;
公众:
mycontainer(T arg){element=arg;}
T增加(){return++元素;}
};
//类模板专门化:
模板
类霉菌容器{
碳元素;
公众:
mycontainer(char arg){element=arg;}
字符大写()
{
if((element>='a')&&(element是否编译?在我看来是个错误。它确实编译。语法正确。@PeteBecker:-OP是负零,因此必须编译;)如果我把模板代码中的<代码> DeviceTypes <代码>改为<代码>类<代码>,我假设他有一个C++概念的编译器作为扩展名。附加了一个完全编译的代码。我很肯定,<代码>朋友<代码>是不相关的。实际上,我不能复制问题,没有<代码>朋友<代码>,所以可能是。我很高兴我没有D。ownvote。你能再教我一点为什么这是必要的吗?@NegativeZero当你指定你想要的输出类型(如运算符)时,它会指定类型,如等。我确实验证了如果我把T放在里面,代码会按预期工作。
friend std::ostream & operator<< <T>(std::ostream & output,
const DeviceType<T> & deviceType );
friend std::ostream & operator<<(std::ostream & output,
const DeviceType<T> & deviceType );
void foo(int);
template <typename T> void foo(T);
int main() {
foo(42); // calls non-template function
foo<int>(42); // calls template function, explicit template argument given
foo<>(42); // calls template function, template argument deduced by compiler
}
// template specialization
#include <iostream>
using namespace std;
// class template:
template <class T>
class mycontainer {
T element;
public:
mycontainer (T arg) {element=arg;}
T increase () {return ++element;}
};
// class template specialization:
template <>
class mycontainer <char> {
char element;
public:
mycontainer (char arg) {element=arg;}
char uppercase ()
{
if ((element>='a')&&(element<='z'))
element+='A'-'a';
return element;
}
};
int main () {
mycontainer<int> myint (7);
mycontainer<char> mychar ('j');
cout << myint.increase() << endl;
cout << mychar.uppercase() << endl;
return 0;
}