vendredi 27 octobre 2017

Using template methods inside template classes

Why is it expecting Struct1 and how do I format it so I can modify the properties in any struct?

I have 1 template class I'm using to modify data in 3 structs containing the same property names, they just happen to use different data types.

I'm trying to use a template method inside my template class, everything seems to be working as I expected it to with the template class upon the various instantiations.

GenericClass<Struct1> inventory[1000];
GenericClass<Struct2> machines[1000];
GenericClass<Struct3> physicalStructures[1000];

(yes I'm aware vectors exist, play along, I am including as little code as possible) That said, when I try to change one of the properties of the structs, I get an error stating that it is expecting the struct, rather than taking any datatype I hand it.

Main.cpp:39:28: error: no viable conversion from 'int' to 'Struct1'
inventory[0].setIdentifier(1);

I've checked these 3 references (and a few more), but they don't appear to do what I am in any of them. How to define template function within template class in *.inl file

Template class with template function

http://ift.tt/2lkUv1H

Here is a sample of my code.

template <class Type>
class GenericClass
{ 
private:
  Type Identifier;
public:
  void setIdentifier(Type Param);
  Type getIdentifier();
};


/* Struct prototypes
************************/
struct Struct1
{
private:
  int Identifier;
  string Description;
  float Value;
}

struct Struct2
{
private:
  long int Identifier;
  string Description;
  float Value;
};

struct Struct3
{
private:
 string Identifier;
 string Description;
 double Value;
};


int main()
{
  GenericRecord<Struct1> inventory[1000];
  GenericRecord<Struct2> machines[1000];
  GenericRecord<Struct3> physicalStructures[1000];
  inventory[0].setIdentifier(1);
}


template <class Type>
void GenericRecord<Type>::setIdentifier(Type Param)
{
  Identifier = Param;
}
template <class Type>
Type GenericRecord<Type>::getIdentifier()
{
  return Identifier;
}

The return method doesn't work either, I'm expecting that they are both failing for similar reasons.

Again, why is it expecting Struct1 and how do I format it so I can modify the properties in any struct?

Aucun commentaire:

Enregistrer un commentaire