【发布时间】:2021-12-26 05:31:19
【问题描述】:
我有以下函数用作二分法
template <typename T>
float bisect(T value, float min, float max, float tol) {
constexpr bool is_function1 = is_numeric_function1<T>::value;
constexpr bool is_function2 = is_numeric_function2<T>::value;
std::cout << is_function1 << " " << is_function2 << std::endl;
if(is_function1) {
...
} else if(is_function2) {
...
}
...
}
一开始,我想检查第一个参数是float(float) 还是float(float, float) 类型的函数,所以我有以下模板
template<typename T, typename = T> struct is_numeric_function1 : std::false_type {};
template<typename T>
struct is_numeric_function1 <typename T,
std::enable_if_t<std::is_same<T, float(float)>::value, T>
> : std::true_type {};
template<typename T, typename = T> struct is_numeric_function2 : std::false_type {};
template<typename T>
struct is_numeric_function2 <typename T,
std::enable_if_t<std::is_same<T, float(float, float)>::value, T>
> : std::true_type {};
对于这样的功能
float f2(float v1, float v2) {
return std::pow(v1, 2) + std::pow(v2, 2);
}
还有这样的电话
std::cout << bisect(f2, 0., 100, 1.)
<< std::endl;
输出总是
0 0
<result>
我怎样才能让它工作?
【问题讨论】:
-
is_numeric_function1有效吗?另外,请说明你是如何打电话给bisect的。 -
这些功能都不起作用,我也更新了问题。
-
我不能reproduce。
-
你真的要推断结构吗?您可以使用 arg
enum {fun1, fun2} type创建 1 个结构并在构造函数中设置类型。