Explicit template specialization

2019-05-14 06:07发布

问题:

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.