Hello, I’m trying to fill in the list of lists, but an error comes out.
There are 2 lists:
struct Lst_Paths
{
char * ID;
Lst_Paths * Next;
Lst_Paths * Prev;
};
struct Lst_Taxi
{
char * ID;
Lst_Paths * Path_Head;
Lst_Taxi * Next;
Lst_Taxi * Prev;
};
And there is a function to fill them:
template & lt; class Type & gt;
Type * Insert (Type * Head, char * ID, bool bval)
{
Type * tmp = NULL;
Type * Prev_to_Next = NULL;
char * PATH_ID;
char choice = 'N';
if (Head == NULL)
{
Head = new Type;
Head- & gt; ID = new char;
Head- & gt; ID = ID;
Head- & gt; Prev = Head- & gt; Next = NULL;
Prev_to_Next = Head;
tmp = Head;
}
else
{
tmp = Head;
while (tmp)
{
Prev_to_Next = tmp;
tmp = tmp- & gt; Next;
}
tmp = new Type;
tmp- & gt; ID = new char;
tmp- & gt; ID = ID;
Prev_to_Next- & gt; Next = tmp;
Prev_to_Next = tmp;
tmp- & gt; Next = NULL;
}
if (bval)
{
tmp- & gt; Path_Head = NULL;
cout & lt; & lt; "Let's set path of texi with ID:" & lt; & lt; tmp- & gt; ID;
do
{
cout & lt; & lt; "Type path ID. \ NFor example: A \ n";
PATH_ID = new char;
cin & gt; & gt; PATH_ID;
tmp- & gt; Path_Head = Insert & lt; Lst_Paths & gt; (tmp- & gt; Path_Head, ID, false);
cout & lt; & lt; "Press Y or y to exit, otherwise press random button to continue. \ N";
cin & gt; & gt; choice;
} while (toupper (choice)! = 'Y');
}
tmp = NULL;
Prev_to_Next = NULL;
return Head;
}
The error itself is on this line:
tmp- & gt; Path_Head = Insert & lt; Lst_Paths & gt; (tmp- & gt; Path_Head, ID, false);
error C2039: Path_Head: is not a member of "Lst_Paths"
I thought that the error is when I try to access
when I call the function again.
Path_Head
but tmp is no longer of type
Lst_Paths
for this I introduced a boolean variable that prevents this function from being entered 3 times. But the error remained, I don’t know what to do anymore. Please do not offer STL lists.
Answer 1, authority 100%
You don’t quite understand how templates work in C++.
Template is a compile-time construct. The templated function is compiled in its entirety, not line by line at runtime.
If you write Insert & lt; Lst_Paths & gt;
, then the entire Insert
function is compiled with the template parameter Type = Lst_Paths
… At the same time, the call tmp- & gt; Path_Head
is also compiled as part of this function, and the compiler does not care deeply that this line will not be executed due to your program logic.
If you want template instantiations to behave differently for different types, you have to learn more about templates. Dig for the partial template specialization.
It seems to me, however, that it makes no sense for your task to make everything so difficult. You can just try to split the function in two.