首页 > 解决方案 > 函数指针的类型特征?

问题描述

我需要有条件地使用模板类std::absstd::fabs模板类,这里是简化版本的相关代码:

template <typename T>
class C
{
public:
    using type = std::conditional_t<std::is_integral_v<T>, std::uint64_t, long double>;
    using check = std::is_integral<type>;

    // ERROR: mismatch in format parameter list
    constexpr auto ptr_abs = check::value ? &std::abs<check::value_type> : &std::fabs;

    // use pointer
    void use_ptr()
    {
        auto x = (*ptr_abs)(-3);
    }
};

没有一个尝试对我有用,我一无所知。

int main()
{
     C<int> a;
     a.f();

     C<float> b;
     b.f();
}

标签: c++typetraits

解决方案


你真的需要使用函数指针吗?利用 C++ 类型安全机制不是更好吗?如下:

template <typename T>
class C
{
public:
    using type = std::conditional_t<std::is_integral_v<T>, std::uint64_t, long double>;
    static const bool check = std::is_integral_v<type>;

    std::function<type(type)> abs = [](auto arg)
    {
        if constexpr (check) return std::abs(static_cast<long long>(arg));
        else return std::fabs(arg);
    };

    void use()
    {
        auto x = abs(-3);
    }
};

对我很有效。请注意,无std::abs符号整数没有,因此,为了避免歧义,我必须通过强制转换来选择特定的重载(long long在这个例子中;我不知道是什么Result)。


在 C++17 之前,没有if constexpr.


推荐阅读