3

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

David
  • 1,398
  • 1
  • 14
  • 20

1 Answers1

5

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.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • I'm still having problems... What should the whole code look like? – David Jan 22 '12 at 14:43
  • Remove 'template<>' in front of 'Array::Array()'. Other errors I get are unrelated to this specific issue: I needed to add `#include ` and `using namespace std;` and I needed to remove the default argument from the _definition_ of templated `Array` constructor (you want default argument in the _declaration_). With these changes it compiles for me using g++, clang, and EDG's front-end. – Dietmar Kühl Jan 22 '12 at 14:56
  • It's strange: `template <>` is needed in gcc. – Naszta Oct 21 '13 at 08:52