Consider a class:
class A
{
int attrib1, attrib2, attrib3;
double attrib4;
std::string attrib5;
int attrib6, attrib7, attrib8, attrib9, attrib10;
public:
// Member functions.
}
Each attrib
variables represent different member variables for various usage and usually related to each other (It might break if there are some mismatches of the values).
For example, I need to access and get the value of attrib4
, attrib5
, attrib6
, attrib7
, attrib8
, attrib9
, attrib10
. To keep the class encapsulated, I must create multiple member functions just to get the variable content or set the individual variable. This is the reason for an idea of a single function to return specific variables by parameter.
I had an idea to use the template for this purpose. First, I created an enum for variable names:
enum class Variable
{
attrib4,
attrib5,
attrib6, attrib7, attrib8, attrib9, attrib10,
};
Then, I created a member function template in class A as follow:
template<typename T>
T get(Variable var)
{
switch (var)
{
case Variable::attrib4:
return static_cast<T>(attrib4);
case Variable::attrib5:
return static_cast<T>(attrib5);
case Variable::attrib6:
return static_cast<T>(attrib6);
case Variable::attrib7:
return static_cast<T>(attrib7);
case Variable::attrib8:
return static_cast<T>(attrib8);
case Variable::attrib9:
return static_cast<T>(attrib9);
case Variable::attrib10:
return static_cast<T>(attrib10);
default:
return 0;
}
}
To use it, I must explicitly specify the variable types as the function cannot automatically deduce the type:
A a;
a.get<std::string>(Variable::attrib5);
The problem of this approach is that this function is error-prone and may be misused (or cannot work at all due to invalid cross conversion).
Are there any solutions for this idea?