views:

57

answers:

1
class RunAround;
class HopUpAndDown;
class Sleep;

template<typename Acts> int doThis();
template<> int doThis<RunAround>()    { /* run run run.. */ return 3; }
template<> int doThis<HopUpAndDown>() { /* hop hop hop.. */ return 2; }
template<> int doThis<Sleep>()        { /* zzz.. */ return -2; }

struct Results
{   
    template<typename Act> int& operator()()
    {
        static int result;
        return result;
    }
};



int main()
{
    Results results;
    //results<RunAround>() = doThis<RunAround>();
    results.operator ()<RunAround>() = doThis<RunAround>();
    results.operator ()<Sleep>() = doThis<Sleep>();
    return 0;
};

If I remove the comment, the compiler thinks I am calling operator() in non-existant template class Results<RunAround> when I want operator<RunAround>() in class Results.

If I want to continue using an operator overload instead of a normal name, am I doomed to use the awful syntax below the comment (which does work)?

+1  A: 

The most comfortable thing is to let template argument deduction work for you:

struct Results {   
    template<typename Act> int& operator()(Act) { /* ... */ }
};

results(RunAround()) = /* ... */;
Georg Fritzsche
But that adds the overhead of instantiating an object, passing a parameter, and requiring a definition of RunAround instead of a simple forward declaration...
Kyle
The overhead is trivial to optimize away for the compiler (at least if the constructor doesn't have side-effects on external objects). As for the need for a definition: if you select a template for that type, i guess you probably want to do something with it anyway. There are only two choices here: you either use argument deduction or specify the template parameter explicitly.
Georg Fritzsche
Johannes Schaub - litb
Ah, indeed - i somehow missed that :) @Johannes
Georg Fritzsche
Accepting this for the sole reason that it's the only answer. I wound up using GMan's suggestion.
Kyle
You don't have to accept it - if you found a solution that suits you better you could provide your own answer. @kyle
Georg Fritzsche