how to inject some code inside function.

Hello. I have the following (simplified) code in the body of a
function:

if (myvar.get_type() == "int")
     dosomething<int> f(func);
     f(myvar.get());
else if (myvar.get_type() == "double")
    dosomething<double> f2(func);
    f(myvar.get());


What I would like to do is to be able to remove the ifs to be able to
inject code
inside this body but from outside the body of the function, maybe with
partial specializations,
but I don't know how to achieve this. Could anyone help me, please?


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
german
2/14/2009 4:50:42 PM
comp.lang.c++.moderated 10707 articles. 0 followers. allnor (8507) is leader. Post Follow

8 Replies
222 Views

Similar Articles

[PageSpeed] 12
On Feb 14, 5:50 pm, german diago <germandi...@gmail.com> wrote:
> Hello. I have the following (simplified) code in the body of a
> function:
>
> if (myvar.get_type() == "int")
>      dosomething<int> f(func);
>      f(myvar.get());
> else if (myvar.get_type() == "double")
>     dosomething<double> f2(func);
>     f(myvar.get());
>
> What I would like to do is to be able to remove the ifs to be able to
> inject code
> inside this body but from outside the body of the function, maybe with
> partial specializations,
> but I don't know how to achieve this. Could anyone help me, please?

You want to call a function on (or with) an object, and would like
the behavior of the function to be selected based on its type?

That's a virtual function.

Template specializations only work at compile time, but clearly your
code is deciding behavior at runtime.  If myvar's type isn't
polymorphic, either it should be, or it should hold a data member
that is that implements the functionality that is changeable.
You might also consider using the visitor pattern, but that's still
an elaboration on a virtual function solution.

If you don't use virtual functions, you'll end up simulating them (or
simulating something very much like them) in your own code, one way
or
another.  You might use templates to help write this simulation, but
I'm not sure how you could escape it entirely.  You might use a
lookup-
table, keyed by your type code, mapped to a function (polymorphic or
otherwise callable object (function pointer, binder, etc), but that's
still essentially a virtual function.

Chris


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Chris
2/15/2009 7:35:57 AM
{ Top-posting is discouraged in this group. See the FAQ for posting guidelines. 
-mod }

You can overload the function.
Create the 2 identical functions with the same name, but with
different dummy argument types:

e.g. void function ( int ) {...} and void function ( double ) {...}

Depending on the actual argument passed in the function call, the
program will automatically choose which function to use.

I hope this is what your looking for, and sorry for the bad english.

On Feb 14, 7:50 pm, german diago <germandi...@gmail.com> wrote:
> Hello. I have the following (simplified) code in the body of a
> function:
>
> if (myvar.get_type() == "int")
>      dosomething<int> f(func);
>      f(myvar.get());
> else if (myvar.get_type() == "double")
>     dosomething<double> f2(func);
>     f(myvar.get());
>
> What I would like to do is to be able to remove the ifs to be able to
> inject code
> inside this body but from outside the body of the function, maybe with
> partial specializations,
> but I don't know how to achieve this. Could anyone help me, please?

{ Edits: quoted banner removed. -mod }


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
ISO
2/15/2009 7:37:59 AM
On 14 f�v, 23:50, german diago <germandi...@gmail.com> wrote:
> Hello. I have the following (simplified) code in the body of a
> function:
>
> if (myvar.get_type() == "int")
>      dosomething<int> f(func);
>      f(myvar.get());
> else if (myvar.get_type() == "double")
>     dosomething<double> f2(func);
>     f(myvar.get());
>
> What I would like to do is to be able to remove the ifs to be able to
> inject code
> inside this body but from outside the body of the function

template<typename F>
typename F::result_type visit(F f)
{
     if(myvar.get_type() == "int")
         return f(myvar.get<int>());
     if(myvar.get_type() == "double")
         return f(myvar.get<double>());

     assert(0);
}

Boost.Variant does that, in an even better way.
I recommend you use it.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Mathias
2/15/2009 7:41:02 AM
german diago wrote:
> Hello. I have the following (simplified) code in the body of a
> function:
> 
> if (myvar.get_type() == "int")
>      dosomething<int> f(func);
>      f(myvar.get());
> else if (myvar.get_type() == "double")
>     dosomething<double> f2(func);
>     f(myvar.get());
> 
> 
> What I would like to do is to be able to remove the ifs to be able to
> inject code
> inside this body but from outside the body of the function, maybe with
> partial specializations,
> but I don't know how to achieve this. Could anyone help me, please?
> 
> 

Obviously you think whatever the above is will be a solution to a
problem you have. Rather than ask us how to implement a solution you
would be better off telling us what problem you are trying to solve.

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Francis
2/15/2009 7:41:15 AM
On 15 feb, 14:41, Francis Glassborow
<francis.glassbo...@btinternet.com> wrote:
> german diago wrote:
> > Hello. I have the following (simplified) code in the body of a
> > function:
>
> > if (myvar.get_type() == "int")
> >      dosomething<int> f(func);
> >      f(myvar.get());
> > else if (myvar.get_type() == "double")
> >     dosomething<double> f2(func);
> >     f(myvar.get());
>
> > What I would like to do is to be able to remove the ifs to be able to
> > inject code
> > inside this body but from outside the body of the function, maybe with
> > partial specializations,
> > but I don't know how to achieve this. Could anyone help me, please?
>
> Obviously you think whatever the above is will be a solution to a
> problem you have. Rather than ask us how to implement a solution you
> would be better off telling us what problem you are trying to solve.
>
> --
>       [ Seehttp://www.gotw.ca/resources/clcm.htmfor info about ]
>       [ comp.lang.c++.moderated.    First time posters: Do this! ]

I think I explained myself in a very bad way, sorry. What I'm looking
for (if it's possible),
is a way to avoid this:

void operator()(value v1, ...)
     if (v1.get_type() == "int")
       dosomething<int>(f)
     else if...
}


I'm doing this because I want to do argument marshalling. For basic
types, this is not a problem.
The problem is that I want to register new types at runtime, and I'd
like them to be marshalled too.
I mean, using function call operator with this prototype:

void operator()(value v1, value v2, value v3);

  Where value holds any registered type in my type system,
I want to be able to add new types at runtime, for use with this kind
of function. And to use it, I must
do argument marshalling inside the function. Anyone knows how to do
this? It's being quite difficult for me.
Thanks in advance.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
german
2/15/2009 6:08:41 PM
german diago wrote:
> On 15 feb, 14:41, Francis Glassborow
> <francis.glassbo...@btinternet.com> wrote:
>> german diago wrote:
>>> Hello. I have the following (simplified) code in the body of a
>>> function:
>>> if (myvar.get_type() == "int")
>>>      dosomething<int> f(func);
>>>      f(myvar.get());
>>> else if (myvar.get_type() == "double")
>>>     dosomething<double> f2(func);
>>>     f(myvar.get());
>>> What I would like to do is to be able to remove the ifs to be able to
>>> inject code
>>> inside this body but from outside the body of the function, maybe with
>>> partial specializations,
>>> but I don't know how to achieve this. Could anyone help me, please?
>> Obviously you think whatever the above is will be a solution to a
>> problem you have. Rather than ask us how to implement a solution you
>> would be better off telling us what problem you are trying to solve.

> 
> I think I explained myself in a very bad way, sorry. What I'm looking
> for (if it's possible),
> is a way to avoid this:
> 
> void operator()(value v1, ...)
>      if (v1.get_type() == "int")
>        dosomething<int>(f)
>      else if...
> }
> 
> 
> I'm doing this because I want to do argument marshalling. For basic
> types, this is not a problem.
> The problem is that I want to register new types at runtime, and I'd
> like them to be marshalled too.
OK now we know the problem.

> I mean, using function call operator with this prototype:
> 
> void operator()(value v1, value v2, value v3);

The first problem is that that must be a member function of some class.
The second problem is that you cannot add overloads or new template
specialisations at runtime.  C++ does not permit the creation of new
types at runtime so your type system must be effectively complete before
  execution of the program. I say effectively complete because there is
a little wriggle room to allow for dynamic libraries.

> 
>   Where value holds any registered type in my type system,
> I want to be able to add new types at runtime, for use with this kind
> of function. And to use it, I must
> do argument marshalling inside the function. Anyone knows how to do
> this? It's being quite difficult for me.

Given that the type must exist before translation has been completed I
think you need a member template. Something along the lines of:

class example {
public:
   template<typename parameter>
    void operator() (parameter p1, parameter p2, parameter p3);
// rest of definition
};

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Francis
2/16/2009 9:15:05 AM
On Feb 16, 2:08 am, german diago <germandi...@gmail.com> wrote:
> What I'm looking
> for (if it's possible),
> is a way to avoid this:
>
> void operator()(value v1, ...)
>      if (v1.get_type() == "int")
>        dosomething<int>(f)
>      else if...
>
> }
>
> I'm doing this because I want to do argument marshalling. For basic
> types, this is not a problem.
> The problem is that I want to register new types at runtime, and I'd
> like them to be marshalled too.
> I mean, using function call operator with this prototype:
>
> void operator()(value v1, value v2, value v3);
>
>   Where value holds any registered type in my type system,
> I want to be able to add new types at runtime, for use with this kind
> of function. And to use it, I must
> do argument marshalling inside the function. Anyone knows how to do
> this? It's being quite difficult for me.

With a map.

typedef std::map<std::string, boost::function<void()> > DispatchMap;
DispatchMap dispatchMap;

// fill the map as necessary

void operator()(value v1)
{
     DispatchMap::iterator f = dispatchMap.find(v1.get_type());
     if (f != dispatchMap.end())
         f(v1);
}

Yechezkel Mett


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Yechezkel
2/16/2009 9:18:23 AM
Hi!

german diago schrieb:
> void operator()(value v1, ...)
>      if (v1.get_type() == "int")
>        dosomething<int>(f)
>      else if...
> }
> 
> 
> I'm doing this because I want to do argument marshalling. For basic
> types, this is not a problem.
> The problem is that I want to register new types at runtime, and I'd
> like them to be marshalled too.

You must either know all the types at compile time, or the new types
must implement marshalling themselves.

Something like:

void marshall(string type, value v)
{
	dosomething<type>(v);
}

will never be possible. You cannot invent new code at runtime.
(Theoretically at runtime you could automatically generate some code,
invoke the compiler to generate a shared object/DLL and load that DLL at
runtime. But you need the source code of the types in order to inspect
their members. And even then, you cannot automatically assign the
correct meaning to these members, whether they need to be marshalled or
not, or whatever)

Back to the problem:
I guess you want to marshall object, either to store them in a file or
database, or you want to marshall objects in order to transfer them over
network and then call a remote function with them.

First can be achived using for example Boost.Serialization:
http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/index.html

Second can be schived using for example ZeroC ICE:
http://www.zeroc.com/

I hope this helps.
Frank

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Frank
2/16/2009 4:21:46 PM
Reply:
Similar Artilces:

ingres error code -6 when issuing a commit
Can anyone tell me what this error code means ? Also, is there a manual that contains all error codes issued by the ingres server ? At 10:00 AM -0800 12/19/2005, JIMC wrote: >Can anyone tell me what this error code means ? Also, is there a >manual that contains all error codes issued by the ingres server ? All the Ingres error codes have funky looking (hex) numbers preceded by E_, W_, or I_ and a two-letter facility code. E.g. E_QE0002 is a generic query execution code. Embedded SQL error codes are different but they are generally largish negative numbers like -38000....

request for matlab code for image compression
dear sir i am in final year B-tech student and i am doing project on image compression using wavelet transform in matlab as well as c programming.I shall be grateful if you can provide me the code as i am unable to do it as soon as possible.i'll be highly obliged if u help me. Thanking you. sushilata. ...

Re: SAS code to C code? #10 1540625
Hi Kai, Maybe this comparison is not the best one, but consider SAS an assembly kit with which to build a prefab. All the semi-finished articles are there and while you can quickly build several variants you can also only build that limited number of variants, which is all you need. Consider C the stones, planks, nails, cement, glue, paint and so on. You have all elements to build anything, incl. something like that prefab, but it takes quite a lot of time. As a matter of fact that prefab has been constructed using these basic elements. Regards - Jim. -- .. . . . . . . . . . . . ...

Re: File Codes HP like 641, 642 etc etc #2
From: "Penney, John" <John.Penney@corr.ca.gov> > Dunno why, but I will not swear- > > I spend a half hour fruitlessly searching the Cognos piece of you-know-what > manuals and Can I Find The HP File Codes? Huh? No I can't. e.g. 644=PH > subfile, 641=Quick screen exec, etc etc I could do better dreaming. I search > the 3000-L archives. Zippo. And slower than molasses on a February morning > in Churchill, Manitoba! > > Would some kind person share with me these codes? If you go to http://groups.google.com And type in: 640 641 group:com...

Change Notification Functions, what are they?
Hi, I'm new to Linux, and am still making my way round the documentation. Apologies if I'm asking an obvious question, but I can't find the answer. I need to use change notification functions, e.g. a mechanism to notify an application when a change in a directory or file occurs. I don't want to poll every directory, it'd be a waste of resources. I've found kevent and kqueue in the BSDs (not Darwin). I've used the Win32 ChangeNotification and the NT CompletionPort functionality. I'm convinced there's got to be something under Linux, but I can...

code compoder studio 3.1 version for TMS320c55x DSK board
HI , i am satish doing my MS. I need c programming code for audio signal compression. The code should be compatible to run on TMS320c55x platform. The software used for this is "code composer studio". Can any help me out fr getting the code for the above topic. Regards satish On Mar 5, 2:36 pm, "satish" <prakash.na...@gmail.com> wrote: > HI , i am satish doing my MS. I need c programming code for audio > signal compression. The code should be compatible to run on > TMS320c55x > platform. The software used for this is "code composer studio". Ca...

Line Method Function
I am using VB5. I wish I had a function to draw a line, giving the angle and length but I do not have the math skills involved to do this. Does anyone have a function that they care to share that does this? I was thinking something like: Public Sub DrawLine(X1 as single, Y1 as single, Len as single, Angle as single, byref X2 as single, byref Y2 as single) and have X2 and Y2 assigned in the Sub (rather than just a line drawn - because I would like to do a little more processing first. The purpose of this is that I have a Square (drawn with the line method) that is cut in half diagonally...

MATLAB r11 string to function
I was wondering if anyone could point me in the direction on how to convert string to function in matlab 5.3? The str2func isnt available in this version unfortunately. Dear Mike! > I was wondering if anyone could point me in the direction on how to convert string to function in matlab 5.3? > > The str2func isnt available in this version unfortunately. To be exact, there are no function handles at all in Matlab 5.3! FEVAL calls a function using the name as string. Kind regards, Jan ...

SQL Injection Attacks by Example
http://shareo.shareo.googlepages.com/sql_injdection.htm ...

Plot 3D function
Hello, I am trying to plot a 3D Function: z = x^2 + y^2 I tried ezplot3('x^2+y^2-z'); but this is not working. What is the correct way to plot a 3D function? Thank You, Miguel "Miguel Moura" <mdNOSPAMmoura@gmREMOVEail.com> wrote in message news:glq5kq$ifu$1@fred.mathworks.com... > Hello, > > I am trying to plot a 3D Function: > z = x^2 + y^2 > > I tried ezplot3('x^2+y^2-z'); but this is not working. > > What is the correct way to plot a 3D function? ezsurf('x^2 + y^2') % or ezsurf(@(x, y) x.^2 + y.^2) -- Steve Lord slord...

Question about mixing c++ exception handling & c code
Hi, I was looking thru code in my organisation. same dll is sharingcode is mixing c++ code & c code, which is being again called by some other c+ + dll. Only issue I am not too sure about exception handling in this case - here is trimmed code snippet - include.h typedef void (func*)(void *,bool); struct scriptparams { func callback; void *obj; }; test.cpp class execption { public: virtual void printerror(){//do something}; }; class foo { public: foo(){}; void dosomething(bool arg) { cout>>"do something">>endl; if(!arg) throw execption; //if valid do someth...

inject does not inject last value
Hi All, inject is a powerful method in ruby. but the ff gives me surprise.. irb(main):001:0> sum=3D0 =3D> 0 irb(main):002:0> [1,2,3,4,5].inject{|sum,e| sum+e } =3D> 15 irb(main):003:0> sum =3D> 10 irb(main):004:0> irb(main):006:0> RUBY_VERSION =3D> "1.8.5" irb(main):007:0> prod=3D1 =3D> 1 irb(main):008:0> [1,2,3,4,5].inject(1){|prod,e| prod*e } =3D> 120 irb(main):009:0> prod =3D> 24 it seems that inject does not update accumulator (sum or prod in = examples) on last iteration. tested on windows and linux. kind regards irb(main):001:...

Need UV 10.1.11 .net VB 2005 Sample Source Code Please
I just installed the DK on my system, and guess what, All samples are in C#. Oh well, Too bad for the poor VB Orphans. Curt wrote: >I just installed the DK on my system, and guess what, All samples are in >C#. Oh well, Too bad for the poor VB Orphans. Curt, I saw your post about UniObjects in the U2 forum. I'm wondering why language-specific syntax is so important. The properties and methods should be the same regardless of language. I'm guessing you just want some plug n play code. At the risk of making it tough for you, I think you'll learn the library b...

Passing variables out of a function #2
Unconscious of this prediction, Mr. Nion continued to occupy precisely the same ground in reference to the Doctor and to Mrs. Strong. I can tell you best what isleta is, by telling you what Doctors Commons is. Lord bless you, no! Not just yet? said my mother, tenderly. I can work. 'But WERE you ever married, Martha? says I. When Agnes wrote to tell me of her safe arrival, I was as miserable as when I saw her going away. 'You are a very Baby! My mother was, no doubt, unusually youthful in appearance even for her years; Audric hung her head, as if it were her fault, poor thing, and said...

POVRay short code contest
The POVRay Short Code Contest entries are now open for voting. This round was limited to no more than 256 bytes, this has still resulted in some quite attractive models/renderings. Point your browsers towards the following to inspect and vote on the entries. http://astronomy.swin.edu.au/scc3/entries/ I hope you will be pleasantly surprised by the quality this round. -- Paul Bourke pdb_NOSPAMswin.edu.au ...

No more Intel Inside
for anyone that feared the new Intel Macs having ugly "Intel Inside" stickers or that annoying tone on TV Commercials, you can now rest easy. Intel is scrapping that Slogan, and changing their 37 year old Company Logo just in time for MacWorld :) Looks like Intel will still grandfather in old companies already using the "Intel Inside" slogan, but going forward get used to "Leap Ahead"... http://money.cnn.com/2005/12/30/technology/intel.reut/index.htm SAN FRANCISCO (Reuters) - Intel Inside is out. The world's biggest chipmaker said Thursday it will scr...

Passing va_list by reference to a function
How can I pass a va_list to another function by reference? In a simple libc implementation I have some functions as follows: static int xprintf(struct callback *cb, const char *fmt, va_list ap) { ... switch (conv_spec) { case 'u': u = get_uint(conv_mods, &ap); ... break; case 'x': u = get_uint(conv_mods, &ap); ... case 'd': n = get_int(conv_mods, &ap); ... ... } } static unsigned long long get_uint(int mods, va_list *ap) { unsigned long long u; switch (mods) { case MOD_NONE: case...

Proper Environment for Source code and Assembler Code
Hi all, I am looking for some nice environment to display C source code and Assembler code. At the moment I do it in the following way: \newenvironment{mylisting} {\begin{list}{}{\setlength{\leftmargin}{1em}}\item\scriptsize\bfseries} {\end{list}} \begin{mylisting} \begin{verbatim} int main() { //do something } \end{verbatim} \end{mylisting} However, I do not think that really looks nice to be honest. Is there maybe a better way to do that instead of the verbatim environment? many thanks, Marcus Marcus <MJones@hotmail.com> writes: > Hi all, > > I am looking for some ...

Avoiding copying when calling function in library created with the MATLAB Compiler
I am writing a method in C++ that needs to pass an array of doubles (allocated with 'new') to a function in a library created with the MATLAB Compiler. Is there a way to pass the array without copying it into an mxArray or mwArray object? "Jim " <jb4140@gmail.com> wrote in message <iapur4$jts$1@fred.mathworks.com>... > I am writing a method in C++ that needs to pass an array of doubles (allocated with 'new') to a function in a library created with the MATLAB Compiler. Is there a way to pass the array without copying it into an mxArray or mwArray ob...

Huffman coding with unequal letter costs
Very interesting: Mordecai J. Golin, Claire Kenyon, Neal E. Young "Huffman coding with unequal letter costs" * http://www.cs.ust.hk/faculty/golin/pubs/LOP_PTAS_STOC.pdf <QUOTE from http://arxiv.org/abs/cs.DS/0205048 > In the standard Huffman coding problem, one is given a set of words and for each word a positive frequency. The goal is to encode each word w as a codeword c(w) over a given alphabet. The encoding must be prefix free (no codeword is a prefix of any other) and should minimize the weighted average codeword size . The problem has a well-known polynomial-time algor...

Preventing JavaScript Injection
Hi, I have a site where users have been granted a lot of flexibility when it comes to entries. They cannot add any code as far as I can see that would harm the server, but they could add JavaScript code that could be harmful to visitors, (or just annoying). So I want to prevent them from running bad scripts on the visitors of their pages. Scripts like... What I was thinking of doing was 1) Send me an email when any user adds an entry with the word "<SCRIPT" in it 2) Send me an email when any user adds an entry with the word "<EMBED" in it 3) Replace "loca...

coding for loadflow
i am in need of codings for loadflow both newton raphson and fast decouled method.pls help me ...

MATLAB code #22
Hi, I am trying to create a plot that should have different characteristics under the described function. Could someone correct this code please. Thanks % Plot a steer angle vs. time t = [0:0.005:10]; for t = 0:1:2 delta = 0*(pi/180); end for t =2:1:2.5 delta = 0.75*(1-cos(2*pi*(t-2)))*(pi/180); end for t = 2.5:1:4.5 delta = 1.5*(pi/180); end for t = 4.5:1: 5 delta = 0.75*(1-cos(2*pi*(t-2)))*(pi/180); end for t = 5:1:5.5 delta = -0.75*(1-cos(2*pi*(t-2)))*(pi/180); end for t = 5.5:1:7.5 delta = -1.5*(pi/180); end for t = 7.5:1:8 delta = -0.75*(1-cos(2*pi*(t-2)))*(pi/180); end for t ...

Re: Fitting complex functions or simultaneous fit of functions with identical parameters with Mathematica
On Friday, June 8, 2012 2:36:22 AM UTC-5, eastman wrote: > Greetings to all! > > I have failed to solve a stubborn problem in fitting a complex- valued > Drude-Lorentz model (DLM) to experimental data using the > NonLinearFitModel of Mathematica. I'd prefer to do the fit with this > procedure since the errors of the experimental data are also known and > that procedure allows for weighting the fit with these errors. > > The problem is as follows: > > In terms of mathematics, the DLM is a complex-valued function of real > arguments or a set...

how do professional PHP developers handle defaults for function parameters?
I'm working in PHP 4. Even if a parameter is mandatory, I nearly always give it a default value of "false". Then I print an error message if someone who is calling my function forgot the mandatory parameter: function outputHtmlToShowFile($fileName=false) { if ($fileName) { // code goes here } else { echo "In outputHtmlToShowAFile() the code expected the first parameter to be a file name, but instead the value was false"; } } How do others handle default parameter values? I've been avoiding this: function outputHtmlToShowFile($fileName) { } ...