C++ template member variable declaration error - class

I'm new to C++ and learning what Class is and related concept on it.
I faced some Error while practicing making code that contains class.
template <typename T>
class Node{
public:
T data;
Node<T> *link;
Node<T>(T element){
data = element;
link = 0;
}
};
template <typename T>
class LinkedList{
protected:
Node<T> *first;
int current_size;
public:
LinkedList(){
first = NULL;
current_size = 0;
};
T GetSize(){
return current_size;
};
void Insert(T element);
virtual bool Delete(T &element);
void Print();
};
template <typename T>
void LinkedList<T>::Insert(T element){
Node *newnode = new Node(element);
newnode -> link = first;
first = newnode;
current_size++;
}
template <typename T>
bool LinkedList<T>::Delete(T &element){
if (first == 0)
return false;
Node *current = first;
Node *previous = 0;
while(1){
if (current->link == 0){
if (previous)
previous -> link = current -> link;
else
first = first -> link;
break; // Point in which Error Occured
}
previous = current;
current = current -> link;
}
element = current -> data;
delete current;
current_size--;
return true;
}
In "delete" Function, "'current': undeclared identifier Error Occured.
I think I declared and defined it at the first of the function (Node* current = this->first).
I don't know why error happened.
Thanks for your help.

Just replace all Node usages with Node<T> and it should compile.
Explanation:
Each class that declares a template (template <typename T>) is familiar with it. Other classes aren't. Even if the template is declared with the same literal T, there isn't a conncetion between two different classes' templates.

Related

c++/cli unmanaged library into managed code

I have the following code in c++/cli
`
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Konstruktorcode hier hinzufügen.
//
delegate int fooProc(UInt16);
}
...
public: void goTest(int x) { // declared in header
fooProc^ managed = gcnew fooProc(this, &Form1::foo);
IntPtr stubPointer = Marshal::GetFunctionPointerForDelegate(managed);
slave[x].module = static_cast<int(*)(unsigned short)>(stubPointer.ToPointer());
...
}
}
public: int foo(unsigned short test) {
Form1::label1->Text = "Hello success !";
...
return 1; // seems to not return to library function ( Run-Time Check Failure #0 - The value of ESP was not properly saved ...)
}
`
then in a static library with native code there is a function which calls the method 'foo' thru the pointer slave[x].module
as following:
int nativefoo(...) {
...
anyStruct[x].module(x); // struct defined in header
...
return 0;
}
The code crashes in method on return. Probably mismatch in calling conventions.
I have no idea how to solve this issue.
I only tried to alter and match the calling conventions. From __clrcall to __cdecl but no affect.

How to call the method of unknown class in MQL?

I've a Collection class which aims to store different kind of objects, however I'd like to call specific method name which these classes share (e.g. ToString()).
Here is my attempt:
class Collection {
public:
void *data[];
void Collection() {}
void ~Collection() {
for (int i = 0; i < ArraySize(data); i++) {
if (CheckPointer(data[i]) == POINTER_DYNAMIC) delete data[i];
}
}
void *Add(void *_object) {
uint _size = ArraySize(data);
ArrayResize(data, _size + 1, 100);
data[_size] = _object;
return _object;
}
string ToString(string _dlm = ",") {
string _out = "";
for (int i = 0; i < ArraySize(data); i++) {
if (CheckPointer(data[i]) == POINTER_DYNAMIC) {
_out += ((void *) data[i]).ToString(); // #fixme: Syntax error.
}
}
return _out;
}
};
However using ((void *) data[i]).ToString() syntax fails with:
'ToString' - member function not defined Collection.mqh
How can I call a ToString() method for each stored object?
It seems to me that it should be something like collection.toString() where collection is an object of your class Collection. Then each object that you add to your collection should implement this function... Maybe it is easier to mention some superclass that supports toString() (or interface with this method) and make sure that you add only correct objects? This also makes your code free of unexpected errors in runtime.
Also CArrayObj is at your disposal with most functions, if you need toString() or any other function then you can simply extend basic class. Maybe the only disadvantage of the default collection is that it stores CObject-inherited objects.
This can be achieved by creating an abstract class where all classes can share the same virtual method. For example:
class Object {
public:
virtual string ToString() = NULL;
};
class Foo : public Object {
public:
virtual string ToString() {
return "Foo";
};
};
class Bar : public Object {
public:
virtual string ToString() {
return "Bar";
};
};
Then in the Collection class the following method:
virtual string ToString(string _dlm = ",") {
string _out = "";
for (int i = 0; i < ArraySize(data); i++) {
if (CheckPointer(data[i]) == POINTER_DYNAMIC) {
_out += ((Object *) data[i]).ToString() + _dlm;
}
}
return _out;
}
Sample usage:
Collection *objects;
objects = new Collection;
Foo *foo = new Foo();
Bar *bar = new Bar();
objects.Add(foo);
objects.Add(bar);
Print(objects.ToString());
delete objects;

Why am I getting access violating reading location when I try to set value of shared_ptr<T> element

I'm getting access violation reading location when I try to set data of class object.
void make_heap_array()
{
//Example of ptr_arr is define: It's define in class variables: vector<shared_ptr<Data_Node<Item>>> ptr_arr;
int total_data = arr_data.size();
for (int i = 0; i < total_data; i++)
{
shared_ptr<Data_Node<Item>> new_node = shared_ptr<Data_Node<Item>>();
Item data = arr_data[i];
new_node->set_data(data); //Error: Access violation reading location
ptr_arr.push_back(new_node);
}
}
Data_Node is class using template with few methods and here is it's code:
template <class Item>
class Data_Node
{
Item info;
public:
const Item& data() const
{
return info;
}
void set_data(const Item& new_data)
{
info = new_data;
}
};
new_node is null (as you might well have checked yourself), so new_node->set_data(data) has undefined behaviour. (The default-constructed state of a shared pointer is null.)

Copying ScriptableObjects

Is there a way of mimicking MonoBehaviour copy semantics in ScriptableObjects?
Say I have a MonoBehaviour like so:
public class DummyClassBehaviour : MonoBehaviour {
public DummyClass DummyClassTest; //ScriptableObject
public DummyClassBehaviour DummyBehaviourTest; //Another DummyClassBehaviour
}
And a ScriptableObject:
public class DummyClass : ScriptableObject {
public string Text = "";
}
When I duplicate(CTRL+D) a GameObject w/ DummyClassBehaviour attached, 'DummyBehaviourTest' copies as you would expect: If it references a MonoBehaviour in the GameObject I'm copying, the copy mechanism updates the reference to the same MonoBehaviour type in the new GameObject. If it references a MonoBehaviour in another GameObject, that reference remains unchanged.
The ScriptableObject, on the other hand, always references the original. So I end up with N GameObject's all sharing the same ScriptableObject (DummyClass) from the original GameObject. I'm using ScriptableObjects to allow serialization of non-Monobehaviour data classes.
As far as I can tell, and please someone correct me if I'm wrong, you cannot modify the serialization behavior of a ScriptableObject to match that of a MonoBehaviour. Namely that it should update references if a duplicate is made.
Instead I opted for a less than optimal solution, but it works. My class is assigned a unique identifier that gets serialized like everything else. I use this ID in DummyBehaviour.Awake() to create a lookup table that I can then use to reassign my DummyClass.
I'm not going to accept my own answer because I don't feel it answers my original question fully, but it's related:
[System.Serializable]
public class DummyClass {
// Unique id is assigned by DummyBehaviour and is unique to the game object
// that DummyBehaviour is attached to.
public int UniqueID = -1;
public string Text = "";
// Override GetHashCode so Dictionary lookups
public override int GetHashCode(){
int hash = 17;
hash = hash * 31 + UniqueID;
return hash;
}
// override equality function, allows dictionary to do comparisons.
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null))return false;
DummyClass item = obj as DummyClass;
return item.UniqueID == this.UniqueID;
}
// Allow checks of the form 'if(dummyClass)'
public static implicit operator bool(DummyClass a)
{
if (object.ReferenceEquals(a, null)) return false;
return (a.UniqueID==-1)?false:true;
}
public static bool operator ==(DummyClass a, DummyClass b)
{
if (object.ReferenceEquals(a, null))
{
return object.ReferenceEquals(b, null);
}
return a.Equals(b);
}
public static bool operator !=(DummyClass a, DummyClass b)
{
if (object.ReferenceEquals(a, null))
{
return object.ReferenceEquals(b, null);
}
return !a.Equals(b);
}
}
And my MonoBehaviour:
[ExecuteInEditMode]
public class DummyBehaviour : MonoBehaviour {
public List<DummyClass> DummyClasses = new List<DummyClass>();
// reassign references based on uniqueid.
void Awake(){
Dictionary<DummyClass,DummyClass> dmap = new Dictionary<DummyClass,DummyClass>();
// iterate over all dummyclasses, reassign references.
for(int i = 0; i < DummyClasses.Count; i++){
DummyClass2 d = DummyClasses[i];
if(dmap.ContainsKey(d)){
DummyClasses[i] = dmap[d];
} else {
dmap[d] = d;
}
}
DummyClasses[0].Text = "All items same";
}
// helper function, for inspector contextmenu, to add more classes from Editor
[ContextMenu ("AddDummy")]
void AddDummy(){
if(DummyClasses.Count==0)DummyClasses.Add(new DummyClass{UniqueID = 1});
else {
// Every item after 0 points to zero, serialization will remove refs during deep copy.
DummyClasses.Add(DummyClasses[0]);
}
UnityEditor.EditorUtility.SetDirty(this);
}
}

Tell me the flow of execution in the following scenario

public class Temp
{
List<T> values = new List<T>;
static Temp()
{
System.Console.WriteLine("static constructor");
}
public Temp()
{
System.Console.WriteLine("general constructor");
}
}
Also please explain me when will the List object will be created and with what type it is created.
}
It appears the field gets initialized first, then the static constructor is called, then the constructor.
class Test
{
string variable = new Func<string>(() =>
{
Console.WriteLine("field initializer");
return "VARIABLE";
})();
static string staticvariable = new Func<string>(() =>
{
Console.WriteLine("static field initializer");
return "STATICVARIABLE";
})();
static Test()
{
System.Console.WriteLine("static constructor");
}
public Test()
{
System.Console.WriteLine("general constructor");
}
}
Test t = new Test();
outuput:
static field initializer
static constructor
field initializer
general constructor
[edit]
Oops sorry, it was a non-static field and I didn't notice it.
The static ctor will be called first.
Then values list will be second and the the ctor.
Read about beforefieldinit here.