c++ compile error
I have this class for double linked lists:
template <typename T>
class Akeraios
{
struct node
{
T data;
node* prev;
node* next;
node(T t, node* p, node* n) : data(t), prev(p), next(n) {}
};
node* head;
node* tail;
public:
Akeraios() : head( NULL ), tail ( NULL ) {}
template<int N>
Akeraios( T (&arr) [N]) : head( NULL ), tail ( NULL ) //meta apo : simainei einai initializer list--arxikopoiisi listas
{
for( int i(0); i != N; ++i)
push_back(arr[i]);
}
bool empty() const { return ( !head || !tail ); }
operator bool() const { return !empty(); }
void push_back(T);
void push_front(T);
T pop_back();
T pop_front();
~Akeraios()
{
while(head)
{
node* temp(head);
head=head->next;
delete temp;
}
}
};
and somewhere in main
int arr[num1len];
int i=1;
Akeraios <int> dlist ( arr );//error line!!
for(i=1;i<=num1len;i++){
double digit;
int div=10;
int j;
for(j=1;j<=i;j++)div=div*div;
digit=number1/div;
int dig=(int) digit;
the error in error line is:
开发者_开发知识库no matching function for call to `Akeraios::Akeraios(int[((unsigned int)((int)num1len))])'
candidates are: Akeraios::Akeraios(const Akeraios&)
note Akeraios::Akeraios() [with T = int]
try this:
Akeraios <int>* dlist = new Akeraios( arr );
your compiler thinks you're calling a function doing it the way you do it.
you could also use the implicit constructor
Akeraios<int> dlist = arr;
(not very nice this is)
This code is perfectly valid and compliant as-is. The only way I can see it messing up is if you had a compiler extension for VLAs and attempted to call the constructor with a variable-length array, which would almost certainly fail. Otherwise, it is perfectly legitimate. Visual Studio accepts without quarrel.
Since you're saying that num1len
is a variable:
Templates are evaluated at compile-time. When you say arr[num1len]
, you're specifying an array with a variable length (is this C99 or something?). The template expects an array with a size that can be evaluated at compile time (you're saying template<int N>Akeraios( T (&arr) [N])
, so there's no way the compiler can match that up.
Just imagine you had a specialization for N=5 or N=10. How would the compiler be able to find the right specialization when compiling the code if the size of the array is not known at that point?
精彩评论