简体   繁体   中英

Type alias and alias template with function datatype

template<typename R, typename... Types>
using Function = R(*)(Types...);

I saw this lines on dev.to

This type alias declaration R(*)(Types...) looks weird to me because there is no function name pointer.

What is this and how can I implement this template?

This type alias declaration R(*)(Types...) looks weird to me because there is no function name pointer.

There is no name since it is supposed to be a type. Take a simpler example:

using IPtr = int*;

The RHS is just a type. It won't make sense to use

using IPtr = int* x;

What is this and how can I implement this template?

It enables declaring and defining of function pointers using a simple and intuitive syntax.

You can use

int foo(double) { ... }
int bar(double) { ... }

Function<int, double> ptr = &foo;

// Use ptr

// Change where ptr points to

ptr = &bar;

// Use ptr more

I find example uses on https://en.cppreference.com/w/cpp/language/type_alias

// type alias, identical to
// typedef void (*func)(int, int);
using func = void (*) (int, int);
// the name 'func' now denotes a pointer to function:
void example(int, int) {}
func f = example;

And this lines are implementation for actual question;

template<typename R, typename... Types>
using Function = R(*)(Types...);
bool example(int&a){
    cout<< a;
    return false;
}
int main()
{
    int a  = 8;
    Function<bool, int&> eFnc =  example; 
    eFnc(a);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM