<p>Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature.  After a little digging, I found that I could do something like the following:</p>

<pre><code>class MyClass
{
protected:
    bool CaseMethod1( int abc, const std::string&amp; str )
    {
        cout &lt;&lt; "case 1:" &lt;&lt; str;
        return true;
    }

    bool CaseMethod2( int abc, const std::string&amp; str )
    {
        cout &lt;&lt; "case 2:" &lt;&lt; str;
        return true;
    }

    bool CaseMethod3( int abc, const std::string&amp; str )
    {
        cout &lt;&lt; "case 3:" &lt;&lt; str;
        return true;
    }

public:
    bool TestSwitch( int num )
    {   
        bool ( MyClass::*CaseMethod )( int, const std::string&amp; );

        switch ( num )
        {
            case 1: CaseMethod = &amp;MyClass::CaseMethod1;
                    break;
            case 2: CaseMethod = &amp;MyClass::CaseMethod2;
                    break;
            case 3: CaseMethod = &amp;MyClass::CaseMethod3;
                    break;
        }

        ...

        bool res = CaseMethod( 999, "hello world" );

        ...

        reurn res;
    }
};
</code></pre>

<p>My question is - <strong>is this the correct way to go about this?</strong>  Should I consider anything that <em>Boost</em> has to offer?</p>

<p>Edit...</p>

<p>Ok, my mistake - I should be calling the method like so:</p>

<pre><code>bool res = ( (*this).*CaseMethod )( 999, "Hello World" );
</code></pre>

[{'answer_id': 56101, 'author': 'Paulius', 'author_id': 1353085, 'author_profile': 'https://Stackoverflow.com/users/1353085', 'pm_score': 1, 'selected': False, 'text': '<p>You can certainly do it, although the CaseMethod call isn\'t correct (it\'s a pointer to member function, so you have to specify the object on which the method should be called). The correct call would look like this:</p>\n\n<pre><code>bool res = this-&gt;*CaseMethod( 999, "hello world" );\n</code></pre>\n\n<p>On the other hand, I\'d recommend <a href="http://www.boost.org/doc/libs/1_36_0/libs/bind/mem_fn.html" rel="nofollow noreferrer">boost::mem_fn</a> - you\'ll have less chances to screw it up. ;)</p>\n'}, {'answer_id': 56111, 'author': 'Anthony Williams', 'author_id': 5597, 'author_profile': 'https://Stackoverflow.com/users/5597', 'pm_score': 4, 'selected': True, 'text': '<p>What you have there is a pointer-to-member-function. It will solve your problem. I am surprised that your "TestSwitch" function compiles, as the calling syntax is slightly different to what you might expect. It should be:</p>\n\n<pre><code>bool res = (this-&gt;*CaseMethod)( 999, "hello world" );\n</code></pre>\n\n<p>However, you might find a combination of boost::function and boost::bind makes things a little easier, as you can avoid the bizarre calling syntax.</p>\n\n<pre><code>boost::function&lt;bool(int,std::string)&gt; f=\n    boost::bind(&amp;MyClass::CaseMethod1,this,_1,_2);\n</code></pre>\n\n<p>Of course, this will bind it to the current <code>this</code> pointer: you can make the <code>this</code> pointer of the member function an explicit third parameter if you like:</p>\n\n<pre><code>boost::function&lt;bool(MyClass*,int,std::string)&gt; f=\n    boost::bind(&amp;MyClass::CaseMethod1,_1,_2,_3);\n</code></pre>\n\n<p>Another alternative might be to use virtual functions and derived classes, but that might require major changes to your code.</p>\n'}, {'answer_id': 56129, 'author': 'Nik', 'author_id': 5354, 'author_profile': 'https://Stackoverflow.com/users/5354', 'pm_score': 0, 'selected': False, 'text': '<p>There\'s nothing intrinsically wrong with the localised example you\'ve given here, but class method pointers can often be tricky to keep \'safe\' if you use them in a wider context, such as outside the class they\'re a pointer of, or in conjunction with a complex inheritance tree. The way compilers typically manage method pointers is different to \'normal\' pointers (since there\'s extra information beyond just a code entry point), and consequently there are a lot of restrictions on what you can do with them.</p>\n\n<p>If you\'re just keeping simple pointers the way you describe then you\'ll be fine, but fore more complex uses you may want to take a look at a more generalised functor system such as <a href="http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html#with_member_pointers" rel="nofollow noreferrer">boost::bind</a>.  These can take pointers to just about any callable code pointer, and can also bind instanced function arguments if necessary.</p>\n'}, {'answer_id': 56160, 'author': 'Vincent Robert', 'author_id': 268, 'author_profile': 'https://Stackoverflow.com/users/268', 'pm_score': 1, 'selected': False, 'text': "<p>I don't see the difference between your call and simply calling the method within the switch statement.</p>\n\n<p>No, there is no semantic or readability difference.</p>\n\n<p>The only difference I see is that you are taking a pointer to a method and so forbids to the compiler to inline it or optimizes any call to that method.</p>\n"}, {'answer_id': 57045, 'author': 'Simon Steele', 'author_id': 4591, 'author_profile': 'https://Stackoverflow.com/users/4591', 'pm_score': 2, 'selected': False, 'text': '<p>You could also build a lookup (if your key range is reasonable) so that you end up writing:</p>\n\n<pre><code>this-&gt;*Methods[num]( 999, "hello world" );\n</code></pre>\n\n<p>This removes the switch as well, and makes the cleanup a bit more worthwhile.</p>\n'}, {'answer_id': 57101, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>Without wider context, it's hard to figure out the right answer, but I sew three possibilities here:</p>\n\n<ul>\n<li><p>stay with normal switch statement, no need to do anything. This is the most likely solution</p></li>\n<li><p>use pointers to member function in conjunction with an array, as @Simon says, or may be with a map. For a case statement with a large number of cases, this may be faster.</p></li>\n<li><p>split t he class into a number of classes, each carrying one function to call, and use virtual functions. This is probably the best solution, buy it will require some serious refatoring. Consider GoF patterns such as State or Visitor or some such.</p></li>\n</ul>\n"}, {'answer_id': 58798, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 0, 'selected': False, 'text': '<p>There are other approaches available, such as using an abstract base class, or specialized template functions.</p>\n\n<p>I\'ll describe the base class idea.</p>\n\n<p>You can define an abstract base class</p>\n\n<pre><code>class Base { virtual bool Method(int i, const string&amp; s) = 0; };\n</code></pre>\n\n<p>Then write each of your cases as a subclass, such as</p>\n\n<pre><code>class Case1 : public Base { virtual bool Method(..) { /* implement */; } };\n</code></pre>\n\n<p>At some point, you will get your "num" variable that indicates which test to execute.  You could write a factory function that takes this num (I\'ll call it which_case), and returns a pointer to Base, and then call Method from that pointer.</p>\n\n<pre><code>Base* CreateBase(int which_num) { /* metacode: return new Case[which_num]; */ }\n// ... later, when you want to actually call your method ...\nBase* base = CreateBase(23);\nbase-&gt;Method(999, "hello world!");\ndelete base;  // Or use a scoped pointer.\n</code></pre>\n\n<p>By the way, this application makes me wish C++ supported static virtual functions, or something like "type" as a builtin type - but it doesn\'t.</p>\n'}]
['https://Stackoverflow.com/questions/56091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2958/']