3

In the spirit of generic programming, I've created the following code:

#include <iostream>
#include <functional>

class Functor
{
public:
    void operator()()
    {
        std::cout << "Functor operator called." << std::endl;
    }
};

void Function()
{
    std::cout << "Function called." << std::endl;
}

void Call( auto & fp )
{
    static int i;
    std::cout << "Unified calling..." << &i << std::endl;
    fp();
}

int main( int argc, char ** argv )
{
    Functor functor;
    std::function< void() > function = Function;

    std::cout << "Begin testing..." << std::endl;
    Call( functor );
    Call( function );
    std::cout << "End testing." << std::endl;

    return 0;
}


Compiled with: g++ main.cpp -std=c++14
output:
Begin testing...
Unified calling...0x100402080
Functor operator called.
Unified calling...0x100402090
Function called.
End testing.

From what I can tell by the address of static, this produces two different functions, so it seems to me like a template shorthand, of a sort. My instinct is that one function to maintain is better than multiple ones, however, besides being mindful of the non-shared static variables, am I missing something that might make this a poor choice, instead of multiple function definitions?

Kit10
  • 1,345
  • 11
  • 12

2 Answers2

8

Yes, there are. They are forbidden by current C++ standard.

void Call( auto & fp )

is a compilation error on standard-conforming compiler.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
-1

It's impossible, is the main flaw.

auto just means type deduction at the point of initialisation. It is not an "any" type. So, using auto in this way would mean your function would have to be a template. In C++17, this will be possible and indeed an auto parameter will automatically make the function a template (personally I find this extremely confusing, but oh well). But for now, no.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • It is exactly *any* type for generic lambdas. – SergeyA Apr 15 '16 at 16:01
  • 2
    @SergeyA Which would be relevant if `Call` were a generic lambda? – Barry Apr 15 '16 at 16:01
  • @SergeyA: It's not - it gets replaced by whatever type has been deduced. The point I'm trying to make (admittedly quite badly) is that `auto` is not a type in itself like some newbies think. An object can't "be" `auto`. And I strongly suspect that misconception is at the heart of this question. – Lightness Races in Orbit Apr 15 '16 at 16:02
  • Possibly. I see what you mean better now, like auto is not `boost::any`. But still, it is not deduction at the point of initializion with generic lambdas, so the statement does not cover all the cases. I think, the answer would be better if reworded with more clarity. – SergeyA Apr 15 '16 at 16:15
  • @SergeyA: The only thing that really matters is that the OP's code is ill-formed. – Lightness Races in Orbit Apr 15 '16 at 16:17