Re: Characterize parameters by type
On Jun 29, 5:31 pm, Rune Allnor <all...@tele.ntnu.no> wrote:
Hi all.
I have an application written in C++ that needs to be
interfaces with matlab. The interface routine needs to
take a number of untyped parameters from matlab
domain, and return a typed object to be passed to the
C++ business routine.
The parameters are:
par1 - vector of either 2 or 4 doubles
par2 - vector of 2 doubles
I would like to implement a test TestParameters that
returns an object which type depends on the combination
of the parameters:
if (par1.size() == 2)
{
if (par2(1) > par2(2))
// return object of class Case1Class
else
// return object of class Case2Class}
else if (par1.size() == 4 )
{
if (par2(1) > par2(2))
// return object of class Case3Class
else
// return object of class Case4Class}
else
{
return 0;
}
I can't see how to wrap this into a function that can
be called from the interface routine.
Any suggestions?
A couple.
Create a class factory that uses polymorphism
Check out boost::any
// Warning all code untested
class Base {};
class Case1Class : public Base {};
class Case2Class : public Base {};
class Case3Class : public Base {};
class Case4Class : public Base {};
// pick the pointer type that best works for you
boost::shared_ptr<Base>
MyClassFactory( X const &par1, Y const &par2 )
{
Base *p = 0;
if (par1.size() == 2)
{
if (par2(1) > par2(2))
p = new Case1Class;
else
p = new Case2Class;
}
else if (par1.size() == 4 )
{
if (par2(1) > par2(2))
p = new Case3Class;
else
p = new Case4Class;
}
return p;
}
/////////////// OR /////////////////
struct X { int a;};
struct Y { float b;};
boost::any MyClassFactory(int a)
{
if(a)
return boost::any( X() );
return boost::any( Y() );
}
void SomeFunct()
{
boost::any b = MyClassFactory(0);
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]