Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ : How to pass function pointer, stored in a local variable, as a template parameter
    primarykey
    data
    text
    <pre><code>using namespace std; float test1(float i){ return i * i; } int test2(int i){ return i+9; } struct Wrapper{ typedef void (*wrapper_type)(int); template&lt;class R, class A&gt; void wrap(string name,R (*fn) (A) ){ wrapper_type f_ = &amp;Wrapper::wrapper1&lt;R,A,fn&gt;; // in the real program, f_ would be passed in an array to some c library wrappers[name] = f_; } void run(int i){ map&lt;string,wrapper_type&gt;::iterator it, end = wrappers.end(); for(it=wrappers.begin();it!=end;it++){ wrapper_type wt = (*it).second; (*wt)(i); } } template&lt;class R, class A, R (*fn) (A)&gt; static void wrapper1(int mul){ //do something A arg = mul; R result = (*fn)( arg ); cout &lt;&lt; "Result: " &lt;&lt; result &lt;&lt; endl; } map&lt;string,wrapper_type&gt; wrappers; }; int main(int argc, char** argv) { Wrapper w; w.wrap("test1",&amp;test1); w.wrap("test2",&amp;test2); w.run(89); return 0; } </code></pre> <p>Here's the g++ error:</p> <pre><code>main.cpp:31: error: ‘fn’ is not a valid template argument for type ‘float (*)(float)’ because function ‘fn’ has not external linkage </code></pre> <p>From what i understand, the problem is that a local variable has no linkage; thus it can not be used as a template parameter. </p> <p>So, i wanted to know if there's a way to get around this problem or another technique to accomplish the same ? </p> <p>Thanks.</p> <p>Edit 1:</p> <p>I totally understand that I can't pass a value that can not be determined at compile time as a template paramter. What i'm asking is - is there a better way to do this? Right now the solution that works for me is :</p> <pre><code>template&lt;class R, class A,R (*fn) (A)&gt; void wrap(string name){ wrapper_type f_ = &amp;Wrapper::wrapper1&lt;R,A,fn&gt;; // in the real program, f_ would be passed in an array to sm c library wrappers[name] = f_; } </code></pre> <p>and called as :</p> <pre><code>w.wrap&lt;float, float, &amp;test1&gt;("test1"); w.wrap&lt;int, int, &amp;test2&gt;("test2"); </code></pre> <p>But here I've to pass argument-type during wrapping. Is there someway to avoid this ? </p> <p>EDIT 2:</p> <p>Just to clarify or add more info: The interface I want to present to the user has to be similar to LuaBind or Boost.Python i.e. Wrapper.wrap("test1",&amp;test1); should be sufficient. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload