【发布时间】:2014-01-12 12:17:30
【问题描述】:
考虑以下程序。我使用h() 作为助手,通过指向来自 cmath 的重载函数的指针来解决歧义:
#include <cmath>
typedef double(*PF1)(double);
typedef double(*PF2)(double, double);
typedef double(*PF3)(double, double, double);
// etc...
auto h(PF1 p) -> decltype(p) {return p;}
auto h(PF2 p) -> decltype(p) {return p;}
auto h(PF3 p) -> decltype(p) {return p;}
int f(int) {return 0;}; // my math function
int main() {
//auto s_ = std::sin; // won't work as std::sin is overloaded
auto s = h(std::sin); // works, type of s is a double(*)(double)
auto p = h(std::pow); // OK.
// auto my_aim = h(f); // my aim is to make h() work with f too
}
在给定函数本身的指针的情况下,是否有一个更智能或更通用的帮助器来推断指向(可能)重载函数的指针的类型,以便推断将“更喜欢”仅涉及双精度类型的重载(作为返回类型和参数)(如果可用)或其他重载之一。
【问题讨论】:
-
类型特征? en.cppreference.com/w/cpp/types 考虑移除指针,观察类型:en.cppreference.com/w/cpp/types/add_pointer
-
是的,你能告诉我如何使用类型特征吗?
-
其实,如果你想存储一个函数,看看std::function en.cppreference.com/w/cpp/utility/functional/function
-
@remyabel 这是我之前的问题 :) 但这是另一回事,将与该答案整合