【问题标题】:Making function pointer typedef from a function typedef in C++?从 C++ 中的函数 typedef 制作函数指针 typedef?
【发布时间】:2014-02-11 21:54:58
【问题描述】:

可以从匹配的函数 typedef 中干净地创建函数指针 typedef 吗?

// Can I define fx_pt in terms of fx_t without duplicating the signature?
// Does decltype allow for any new sort of trick here?
using fx_t  = char(int, char, std::vector<float> const &);
using fxp_t = char(*)(int, char, std::vector<float> const &);

// Using function typedef to enforce interface for declarations and definitions.
fx_t foo, bar, baz;
char foo(int) { /* ... */ }

// Using fp typedef elsewhere as normal.
fxp_t whatever{bar};
whatever(99);

我从不期望函数(指针)typedef 语法对我来说是完全直观的,但我无法确定是否可以消除重复代码。

这可能与在类/原始类型定义和类/原始指针类型定义之间转换的更大问题有关,我记得听说不能在...之间进行可移植转换...

【问题讨论】:

    标签: c++ c++11 typedef using


    【解决方案1】:

    只需在函数别名中添加*

    using fx_t  = char(int, char, std::vector<float> const &);
    using fxp_t = fx_t*;
    

    Live demo

    【讨论】:

    • std::add_pointer 值得一提的是恕我直言,虽然它本质上是做同样的事情 (en.cppreference.com/w/cpp/types/add_pointer)
    • @zahir add_pointer 在一个现已删除的答案中被提及 :-)(您需要 10k 代表才能看到它)
    • @zahir 我认为std::add_pointer 是我希望在交给我的代码中看到它的方式。这使得 100% 清楚代码应该做什么而无需怀疑这是否是 * 和函数 typedefs 的另一个奇怪的事情。
    猜你喜欢
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2010-12-08
    • 1970-01-01
    相关资源
    最近更新 更多