2

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

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

有什么办法如何使用语法

逃避在C++ 2003或C++ 0x中这个问题
using (*f_function)(T, T, T); // something like that 

我想使用指针的函数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;} 

并在构造初始化它的值。随后:

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

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

+1

我敢肯定C++ 03允许类型定义不完整类型:'struct X; typedef X Y;' –

回答

5

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

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

例如:

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; 
} 
+0

感谢您的快速解决方案。 – justik