Explicit template specialization

女生的网名这么多〃 提交于 2019-12-22 10:26:41

问题


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}' : 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

Thanks


回答1:


The implementation of the specialization's constructor isn't a template! That is, you just want to write:

Array<float>::Array()
{
    std::cout << "Error";
}

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.



来源:https://stackoverflow.com/questions/8961545/explicit-template-specialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!