这里说我有一个简单的模板功能,原则上可以接受所有类型:
template <class Type>
std::ostream& operator<< (std::ostream& stream, const Type subject) {
stream << "whatever, derived from subject\n";
return stream; }
Run Code Online (Sandbox Code Playgroud)
我只想用这个模板来讨论几种类型,比如std :: vector和boost :: array对象.但是每当我使用cout到其他类型甚至基本类型时,例如std :: cout << int(5);,都会出现编译错误,因为现在有两种可能的operator <<(std :: ostream,int)实现一个是标准的c ++,另一个是我的模板函数.
我想问一下,是否可以限制我的模板功能,以便它只接受我指定的几种类型?这是当我使用cout << int(5)时告诉编译器忽略我的模板的方法.提前致谢.
更清楚,这就是我想要做的:
template <class Type>
std::ostream& operator<< (std::ostream& stream, const Type subject) {
if (Type == TypeA or TypeB or TypeC) //use this template and do these {...};
else //ignore this template, and use operator<< provided in standard c++ library.
}
Run Code Online (Sandbox Code Playgroud) 我正在编写一些代码,在这些代码中std::vector<double>,在指定值之前声明了一个类型的变量.我无法与声明一起定义值,因为它需要多行代码来设置值.问题在于,这个变量本质上是一个常量,这意味着它一旦设置就不应该被修改.但是,它无法声明const.
一种方法是创建另一个变量,const并将值复制到其中.const std::vector<double> a(b);会这样做,而a不是b在程序中使用.但是,我的变量可能很大,我希望学习除了必须执行复制之外的其他方法.
你们有什么建议吗?
我试图找到这个,但找不到任何.我知道我可以创建一个数组变量的引用:
int x[10] = {}; int (&y)[10] = x;
Run Code Online (Sandbox Code Playgroud)
但是,在编译时不知道数组大小的情况下,如下面的代码所示:
const int n = atoi( string ); //the string is read from a text file at run time.
int x[n] = {}; int (&y)[n] = x; //this generates a compiling error.
Run Code Online (Sandbox Code Playgroud)
即使int n被声明为const,只要在编译时不知道n,引用就是无效的.编译器会这样说:类型'int [n]'的引用不能绑定到不相关类型'int [n]'的值.任何人都知道如何解决这个问题?提前致谢.