samedi 28 février 2015

C++ template for variable type declaration


I have a number of classes with differing members, all of which have operations of the following type



::basedata::Maindata maindata;
::basedata::Subdata subinfo("This goes into the subinfo vector");
subinfo.contexts(contextInfo);
maindata.subdata().push_back(subinfo);


Note that I am asking how to set up generalized templates to perform these actions. I cannot set up a special case for each type of maindata and subinfo. I also need to be able to see how to call the template from my main code. I have been able to set up a template if maindata.subdata() exists, but keep getting a compilation failure on a call to the template if it does not exist. That is create the template of the form



perform_Push(maindata.subdata(), subinfo);


so that it can be compiled whether or not maindata.subdata() exists or not.


I could accept templates that build so that the main code can show



bool retval
retval = hasmember(maindata, subdata);
if (retval)
{
buildmember(maindata.subdata, subinfo);
setAttributes(subinfo, data);
perform_Push(maindata.subdata(), subinfo)
}
else
{
// Perform alternate processing
}


As of now, the code inside the if would not compile when the templates being called should just be void.


While ::basedata::Maindata is always defined, ::basedata::Subdata may or may not be defined depending on the release of libraries that my code is being build with. subdata is defined as a vector belonging to maindata which therefore has the push_back() operation defined. There are too many types of subData to create a separate template for each type as T::Subdata within a template in any case.


That is, if subdata was the only case, I could create a specialization of the template T as ::maindata::subdata and a generic Template T.


I do not have any control of the include files or library that for this so that I cannot create a #define of a variable to test with the pre-compiler. Is there a good way of setting up a template that would allow this to work? I could use a template that returns a boolean true (success) or false (no such definition) and call the alternate processing at run time. I would not need to have an alternate template.


Basically, I am asking how to apply SFINAE to this particular situation.


I have managed to figure out what I need to do to set up the basic template


If I have the most basic operation



maindata.subdata().push_back(data)


I can define a template of the form,



<template class T, typename D>
auto doPush(D data) -> decltype(T.pushback(data), void())
{
T.push_back(data);
}


and the call would be



doPush<maindata.subdata()>(data);


However, the problem would be how to set it up when maindata does not yet have a member subdata.




Aucun commentaire:

Enregistrer un commentaire