Can I access a struct passed into a template generically? - c++

As per the title, this is what I am looking to do. Basically I am looking to load in structures from files, but support every kind of structure, so I am attempting to do it in a template. This is my first time using templates really so excuse my ignorance!
I want to be able to do something like:
template<class T> T ConfigLoader::LoadStructFromFile(T a)
{
int noOfThingsInStruct;
noOfThingsInStruct = a[1];
return a;
}
Is this at all possible?
My function does sorting of the string loaded in from files etc but thought I would leave that part out.
I want to be able to get this value to use it to loop and give the struct the correct number of values it is looking for.

So you want to dynamically figure out what members and methods are in a struct? Similar to, say, what you can do in Javascript in runtime, but in compile time? No, you can't. However, you can make a template policy and base this function on that.

Simple answer: impossible.
Long answer: still no.
Detour:
you can use something based on type traits. Create a template class numberOfElements<typename T> and overload it for every struct you need with a value you expect. Then, use it in your LoadStructFromFile, since you know T.
You can also use SFINAE to test for some function that'll return the number of elements in a struct. If a given class/struct implements it, just use it to get the number of members. If not - assume there's only 1 member (or whatever you wish).

Related

void*, extension and template. pros and kontras

Sometimes I have a problem and see 3 ways of implementing the solution. I want to know when to use which of these 3 different implementations. Below there are some exsamples, to see what I mean. I also wrote some pros/kontras which I think is correct. If something seems to be wrong, then please tell me and I'll change that.
void* example:
void method(void* value)
{
//save value as member
}
pro void*:
void* can save every type and you don't have to use templates (in headers).
kontra void*:
-when you have a list of void* you can store in index[1] another type than in index[2] which is critical, because you don't know which type it is. But with dynamic_cast you can check if you can cast it to the type or not.
-when you have a void* list with entities of the same class which have 2 variables, you can not sort by variable1 / variable2 without casting it back to the original class.
Extension exsample:
Creating a new class and extent it on another class:
class CTestClass
{
void Method1();
};
class CTest2 : CTestClass
{
//use somehow the method
};
std::vector<CTestClass> list;
pro Extension:
this way of implementing a class can be usefull, if you need a method which is in every object you need. For example you want to sort by a variable. In such a method you can make the compare.
kontra Extension:
much effort
exsample template:
template <class T>
class CTest
{
//do some stuff
};
pro template:
in a template list, you can not add different types at the same time.
kontra template:
when you have a template list of type T and T has for exsample 2 variables. You can not say: sort by variable1 or variable2 because you can not get into the class T.
As far as I know: you have to implement the template into the header file, which is ugly to see.
I hope everyone understands what I mean.
Is void* a good way to program?
Can I write templates also in .cpp files?
What do you think when to use which of this techniques? Is there some kind of rule?
The statement below is incorrect
pro void*:
void* can save every type and you don't have to use templates (in
headers).
Templates haver their closest equivalent in cross macros and not in void pointers, but exist for a different set of purposes than the mere polymorphism afforded by void pointers. Using void pointers in no way substitutes templates.
While modern programmers might not recommend about using void pointers, complaining about the (true!) potential dangers afforded, old school C-style code certainly has a use for them and this is the reason they exist. Pairing the benefits gained from void pointers with the tradeoff in performance by the C++ dynamic cast, would simply spoil the choice.
Void pointers just exist to offer limitless flexibility at managing memory when you know what you are doing and should be used only in that case. There is no comparison between them and templates.
A method that takes a void * argument should only exist when:
Case 1: The size of the passed data is known and the argument is considered as raw data. It makes no difference what that data is.
Case 2: The size of the passed data is known and you plan to convert it to a pointer of the appropriate type later (for example by some parsing, enumeration policy, known type, etc) but in order to go through some general purpose functions, libraries, APIs, you must convert it to known-length void* inbetween.

Store any value and a value of a specific range of classes

I have a class that looks something like this:
class container{
private:
std::vector<physical_component> physical;
std::vector<storage_component> storage;
--some other stuff not relevant--
public:
--constructors, getters setters, methods to add to the vectors etc--
}
Now I am struggeling with making the physical_component and storage_component classes since I dont know a proper datatype to handle this sort of thing.
Physical_component should be able to:
Store a set amount of types, and fully retaining a type (something I can cast to is good enough)
Should store the objects in a way that makes them individual from the ones passed (and therefore secure from changes to the orignial class)
I remember something like that excisting in c alongside enum but I dont know the name. Also c++ probably has a better way for that.
Storage_component is supposed to:
Store any type
(optional) remember the original type
I have no idea how to achieve this properly. I saw std::any but it seems to be rather new therefore I dont know if its a good way to go about this. Also I cant make storage_component a template because I cant store it in a vector then
What is the (proper) way to implement these classes?
Store a set amount of types, and fully retaining a type
You probably want std::variant<Ts...> (or boost::variant<Ts...>). It stores one of Ts... at a particular point in time.
Store any type
If all the types share the same interface, use a traditional virtual + std::unique_ptr polymorphism approach. Otherwise std::any is the right choice here.

A C++ program with user-defined variables

I'm writing a code that implements simple command line calculator, and I wanted to add a function for user to create his own variables with numeric values for better calculations. Can anyone share any advice, what technique should I use? I thought about creating an allocated two-dimensional string array and later just converting numeric values or use a template, something like that:
template<class T>
void UserVariables(T varname, T varvalue){
T tArray[2][MAX_VARS]={ {varname1, varvalue1}, {varname2, varvalue2}, ... };
....
}
Maybe there are any better and less noobie-ish decisions out there? Thanks in advance.
Your options are here:
std::unordered_map
std::map
std::unordered_multimap
std::multimap
I don't see how your attempt would work - templates are evaluated at compile time, not run time, so the user can't make new variables one the code is running.

Define std::hash<std::function>

I need to create a templated class that can hold pointers to elements of type T and then performs functions on them. The functions will come from different places, so I need a container to store them, so I can call them later. I decided to use an std::unordered_set, because it offers speed and restricts duplication due to it being implemented as a hash table. I have a whole class written, but it doesn't compile due to there not being a hash function defined for my std::function that takes a pointer of type T and returns void. It's easy enough to specify it with struct hash<std::function<void(MyCustomType*)>> (and overloading the () operator, too) for each type I use, but how do I actually hash the function?
Here is a watered-down excerpt from my class with the relevant members and methods:
template <typename T>
class Master {
private:
std::unordered_set<std::function<void(T*)>> functions;
protected:
registerFunction(std::function<void(T*)> function) {
this->functions.insert(function);
}
unregisterFunction(std::function<void(T*)> function) {
this->functions.erase(function);
}
};
I'm not completely bound to using an std::unordered_set, but it seems to offer everything that I'd need to get this piece (and the rest of my code) working well.
Am I thinking about this the wrong way? Is it completely impossible to hash a std::function?
A set is mostly something you will check that data is in it.
So I do not see the point of using one here... You'll have your functions and you'll store them in the set, and after that, what ? You just iterate on them ?
For your question, a element of a set should have a way to generate a hash and an operator==(). The second is not provided for std::function and thus you wouldn't be able to check that your function is really in the set.
So even if you find a way to generate an hash from the function, you would be stuck... And I do not see how to meet the hash requirement.
Why not simply use a std::vector ?

How to allow your data structure to take in objects of any class - C++

How do I do that? Like you know in Java, you can use an ArrayList and it will take any object as long as you cast it down to whatever it is when you're retrieving the object.
Even better, you can specify what class of objects that ArrayList would store by doing...
new ArrayList()< whateverObject >
I've implemented a linked list data structure in C++ and I'd like to know how I can allow it to do this...
At the moment, I'm just using...
typedef whateverObject ItemType
at the start of my header file for my linked list and then manipulating "ItemType" throughout the implementation of the linked list. So every time I want to change the type, e.g. instead of using the list for storing strings, I want to store an int, I'll have to change the typedef in my linked list's header but I want to be able to simply use it for any object so...
How?!
Thanks.
Templates are the answer to your question.
Define your linked list as follows :
template<typename ItemType>
class ArrayList
{
// What's inside your class definition does not need to be changed
// Include your method definitions here and you'll be fine
};
The type to use is then ArrayList<WhateverObject>.
Use templates. It's a lot to explain so I'll just give you a link where it's explained much better than I'll ever be able to do here: C++ FAQ - Templates.
While you're at it, if you have the time, I suggest you read the whole FAQ, it's really a great resource!
If I have understood well what you ask, templates is what you want.
Take a look here:
http://www.cplusplus.com/doc/tutorial/templates/
In java you can do so, because all classes are inherited from one base class Object. In C++ you do not have it. The reason is that Object base class impose overhead for all objects, while C++ do not like any unnecessary overhead.
If you want to store any object - you can store "void *" data type. The question remained - what you will be able to do with objects, without the knowledge of the type? If you do know - you can cast to the needed type and use it. The practice described above is not safe, and templates are better in most cases.