C++ 为什么这个模板不能编译?
我有一个非常简单的模板,它是一个容器,是一个T数组。我得到一个语法错误: container.h(7):错误C2143:语法错误:缺少“;”在“&”之前。我已经尝试删除那里的声明,但是错误只是跳过了定义。非常感谢您的帮助 编辑:现在我修复了使用名称空间的问题,但出现了另一个错误: container.h(8):错误C2975:“container”:未命名参数的模板参数无效,应为编译时常量表达式C++ 为什么这个模板不能编译?,c++,templates,generic-programming,C++,Templates,Generic Programming,我有一个非常简单的模板,它是一个容器,是一个T数组。我得到一个语法错误: container.h(7):错误C2143:语法错误:缺少“;”在“&”之前。我已经尝试删除那里的声明,但是错误只是跳过了定义。非常感谢您的帮助 编辑:现在我修复了使用名称空间的问题,但出现了另一个错误: container.h(8):错误C2975:“container”:未命名参数的模板参数无效,应为编译时常量表达式 #include <typeinfo.h> #include <assert.h&
#include <typeinfo.h>
#include <assert.h>
#include <iostream>
#pragma once
using namespace std;
template <typename T, int> class Container;
template <typename T, int> ostream& operator<< <>(ostream &, const Container<T,int> &);
template<class T , int capacity=0> class Container
{
//using namespace std;
private:
T inside[capacity];
public:
Container()
{
}
~Container(void)
{
}
void set(const T &tType, int index)
{
assert(index>=0 && index<= capacity);
inside[index] = tType;
}
T& operator[](int index)
{
assert(index>=0 && index<= capacity);
return inside[index];
}
friend ostream& operator<< <>(ostream& out, const Container<T,int> c);
{
for(int i=0;i<sizeof(inside)/sizeof(T);i++)
out<<c.inside[i]<< "\t";
return out;
}
};
#包括
#包括
#包括
#布拉格语一次
使用名称空间std;
模板类容器;
模板ostream&operator=0&&index=0&&index您可能需要:
template <typename T, int N>
ostream& operator<<(ostream &, const Container<T,N> &);
// ^ here you need N, not int!
模板
ostream&operator您可能需要:
template <typename T, int N>
ostream& operator<<(ostream &, const Container<T,N> &);
// ^ here you need N, not int!
模板
ostream&operator您想要的是:
template <typename T, int N>
friend ostream& operator<<(ostream & out, const Container<T,N>& c) {
for(int i=0;i<sizeof(inside)/sizeof(T);i++)
out<<c.inside[i]<< "\t";
return out;
}
模板
friend ostream&operator您想要的是:
template <typename T, int N>
friend ostream& operator<<(ostream & out, const Container<T,N>& c) {
for(int i=0;i<sizeof(inside)/sizeof(T);i++)
out<<c.inside[i]<< "\t";
return out;
}
模板
friend ostream&Operator也要编写ostream运算符编辑后,您仍然会遇到我在回答中指出的问题:容器
无效,您需要Container
。还要编写ostream操作符。编辑之后,您仍然会遇到我在回答中指出的问题:Container
无效,您需要Container
。此代码有效,但请简要解释一下,如果我已经在模板类中,为什么需要重复该模板操作?非常感谢。@OrCyngiser,因为类中定义的friend
函数不是类的一部分。此代码有效,但请简要解释一下,如果我已经在模板类中,为什么需要重复模板操作?非常感谢。@OrCyngiser,因为类中定义的friend
函数不是类的一部分。