C++,指向函数的指针作为新类型

jus*_*tik 2 c++ function-pointers parameter-passing generic-programming

在C++ 2003中,typedef只能用于完整类型.因此,不允许创建指向函数的指针和通用T作为类型:

template <typename T>
typedef T(*f_function)(T, T, T);
Run Code Online (Sandbox Code Playgroud)

有没有办法如何使用语法在C++ 2003或C++ 0x中回避这个问题

using (*f_function)(T, T, T); // something like that
Run Code Online (Sandbox Code Playgroud)

我想使用指向函数fff的指针作为类成员

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;}
Run Code Online (Sandbox Code Playgroud)

并在构造函数中初始化其值.随后:

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

这种结构安全吗?有没有其他方法可以解决这个问题?谢谢你的帮助.

mar*_*inj 5

您可以使用别名模板(C++ 11)声明:

template <typename T>
using f_function = T(*)(T, T, T);
Run Code Online (Sandbox Code Playgroud)

例:

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;
}
Run Code Online (Sandbox Code Playgroud)