【问题标题】:C++, pointer to a function as a new typeC ++,指向函数的指针作为新类型
【发布时间】:2016-10-10 17:09:30
【问题描述】:

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

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);
}

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

【问题讨论】:

  • 我很确定 C++03 允许 typedef 不完整的类型:struct X; typedef X Y;

标签: c++ parameter-passing function-pointers generic-programming


【解决方案1】:

您可以使用别名模板 (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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多