显式模板专门化 [英] Explicit template specialization
问题描述
我讨厌提出这样一个一般性的问题,但下面的代码是在显式模板专业化的练习。我一直收到错误:
I hate to ask such a general question, but the following code is a exercise in explicit template specialization. I keep getting the error:
c:\users\ *** \documents\visual studio 2010\projects\\ \\ template array\template array\array.h(49):error C2910:'Array :: {ctor}':不能显式专用
c:\users\***\documents\visual studio 2010\projects\template array\template array\array.h(49): error C2910: 'Array::{ctor}' : cannot be explicitly specialized
#ifndef ARRAY_H
#define ARRAY_H
template <typename t>`
class Array
{
public:
Array(int);
int getSize()
{
return size;
}
void setSize(int s)
{
size = s;
}
void setArray(int place, t value)
{
myArray[place] = value;
}
t getArray(int place)
{
return myArray[place];
}
private:
int size;
t *myArray;
};
template<typename t>
Array<t>::Array(int s=10)
{
setSize(s);
myArray = new t[getSize()];
}
template<>
class Array<float>
{
public:
Array();
};
template<>
Array<float>::Array()
{
cout<<"Error";
}
#endif
感谢
推荐答案
专业化的构造函数的实现不是一个模板!也就是说,您只需要写:
The implementation of the specialization's constructor isn't a template! That is, you just want to write:
Array<float>::Array()
{
std::cout << "Error";
}
实际上,你似乎想限制使用'Array'类模板不能与float一起使用,在这种情况下,您可能只希望声明而不是 define ,以将运行时错误转换为编译时错误:
Actually, it seems that you want to restrict the use of your 'Array' class template to not be used with 'float' in which case you might want to only declare but not define you specialization to turn the run-time error into a compile-time error:
template <> class Array<float>;
当然,有很多变体如何阻止实例化类。但是,创建运行时错误似乎是最糟糕的选择。
Of course, there are many variations how you can prevent instantiation of classes. Creating a run-time error seems to be the worst option, however.
这篇关于显式模板专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!