简体   繁体   中英

C++, pointer to a function as a new type

In C++ 2003, typedef may be used only on a complete types. Hence, it is not allow to create pointer to a function and the generic T as a type:

template <typename T>
typedef T(*f_function)(T, T, T);

Is there any way how to evade this issue in C++ 2003 or in C++0x using a syntax

using (*f_function)(T, T, T); // something like that

I would like to use the pointer to a function fff as a class member

template <typename T>
class A
{
public:
    f_function fff;

    A() {fff = NULL;}
    A( f_function pf){fff = &pf;}
};

template <typename T>
T f1(T x, T y, T z) {   return x + y + z;}

template <typename T>
T f2(T x, T y, T z) {   return x - y - z;}

and initialize its value in the constructor. Subsequently:

int main()
{
A <double> a(f1);
double res = a.getX(1.1, 2.2, 3.3);
}

Is this construction safe? Is there any other way how to solve this problem? Thanks for your help.

You may use alias template (C++11) declaration:

template <typename T>
using f_function = T(*)(T, T, T);

example:

http://coliru.stacked-crooked.com/a/5c7d77c2c58aa187

#include <iostream>
#include <string>
#include <array>

template <typename T>
using f_function = T(*)(T, T, T);

template <typename T>
class A
{
public:
    f_function<T> fff;

    A() {fff = NULL;}
    A( f_function<T> pf){fff = pf;}
};

template <typename T>
T f1(T x, T y, T z) {   return x + y + z;}

template <typename T>
T f2(T x, T y, T z) {   return x - y - z;}

int main()
{
A <double> a(f1);
double res = a.fff(1.1, 2.2, 3.3);
std::cout << res;
}

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