开发者

How can you use a "function type"?

In C++ you can create a "function type" with for example:

void main() {
 int a();
}

And a has the type "int ()", but is it possible 开发者_JS百科to use it? I can't even pass 'a' as a template argument (but I can pass "int ()" as one)


You are not declaring a "function type". You are declaring a function. This is the same thing that you normally do in file scope, but in this case you do it in local scope

int main() {
   int a(); /* declare function `a` */
   ...
   int i = a(); /* call function `a` */
}

int a() { /* define function `a` */
  /* whatever */
}

And yes, you can pass it as a template argument. It has to be a non-type argument, of course

template <int A()> void foo() { 
  A(); /* call the function specified by the template argument */
}

int main() {
   int a(); /* declare function `a` */
   foo<a>(); /* pass it as a template argument */
}


First, a correction: this is not a definition of a "function type". It's the declaration of a function.

Second, sure you can use it:

void main() {
    int a();

    a(); // call the function!
}

Of course the linker will complain that there is no function int a() defined anywhere, but that's another issue entirely.


That's a prototype declaration.

int main(int argc, char **argv) {
    int a();
    int result = a();
}

int a() { return 42; }

Maybe you actually meant a function pointer?

int target() { return 42; }

int main(int argc, char **argv) {
    int (*a)();
    a = target;
    int result = a();
}


You will need to define int a(); this is a forward declaration, which means that you can call a() within main() without having to give the function prototype above main().

#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {
        int a();
        a();
        return 1;
}

int a() {
        cout<<"Hello world"<<endl;
}


You can create a function type by overloading the function call operator, operator(). For example:

class MyF {
    int x_;
    public:
    MyF(int x) {
        x_ = x;
    }
    public:
    void operator()(int y) {
       // do something with x, y.
    }
}

int main() {
    MyF f(3); // create function object

    f(4); // call it 
}


Now, multiple others have already pointed out that you're declaring a function there, not a type. No need to go into that further.

Also you cannot declare or define "new" function types, only functors (see Kevin's response). Of course they still exist, just you cannot define them and you also don't have to. Just like pointer or reference types, you can just "use" them when needed.

However you can typedef a function type. You can then use that alias (typedef) to declare pointers to functions, or (less known), even functions of that type:

typedef int IntToIntFn(int);

IntToIntFn foo; // same as 'int foo(int);'
IntToIntFn* bar; // same as 'int (*bar)(int);'

int main()
{
    foo(42);
    bar = &foo;
    bar(42);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜