【问题标题】:C++ get return type for template argumentC++ 获取模板参数的返回类型
【发布时间】:2021-04-22 22:43:33
【问题描述】:

我有

template<typename DistanceFunc>
class C
{
    using DistanceType = // the return type from DistanceFunc

public:
    C(DistanceType distance, DistanceFunc f)
    : m_distance(distance),
      m_f(f)
    {}

private:
    DistanceType m_distance;
    DistanceFunc m_f;
};

如何从DistanceFuncDistanceType 派生返回类型?

【问题讨论】:

    标签: c++ templates type-deduction return-type-deduction


    【解决方案1】:

    如何从 DistanceFunc 中为 DistanceType 派生返回类型?

    另一种解决方案是使用模板专业化。

    您可以将C 声明为接收typename,而无需定义它

    template <typename>
    class C;
    

    然后你可以定义一个接收(指向)函数类型的 C 的特化,如下所示

    template <typename DistanceType, typename ... Args>
    class C<DistanceType(*)(Args...)>
     {
       using DistanceFunc = DistanceType(*)(Args...);
    
    public:
        C(DistanceType distance, DistanceFunc f)
        : m_distance(distance), m_f(f)
        {}
    
    private:
        DistanceType m_distance;
        DistanceFunc m_f;
    };
    

    如您所见,函数类型被解析为返回类型和参数类型。现在DistanceType 被简单地推导(作为返回类型),你必须重新创建DistanceFunc

    你可以如下使用它

    int foo (int, long)
     { return 0; }
    
    // ...
    
    C<decltype(&foo)> c0{0, &foo};
    

    从C++17开始还可以添加推演指南

    template <typename DistanceType, typename ... Args>
    C(DistanceType, DistanceType(*)(Args...)) -> C<DistanceType(*)(Args...)>;
    

    所以你可以简单地声明一个C 对象

    C c0{0, &foo}; // C<decltype(&foo)> is deduced
    

    【讨论】:

      【解决方案2】:

      如何从 DistanceFunc 中为 DistanceType 派生返回类型?

      视情况而定。 DistanceFunc 类型的函数怎么调用?

      假设用int 调用,你可以尝试一下

      using DistanceType = decltype(std::declval<DistanceFunc>()(std::declval<int>()));
      

      如果您有从DistanceFunc 接收的类型,则使用decltype()std::declval() 可以模拟对函数的调用并获取结果类型。

      【讨论】:

        猜你喜欢
        • 2012-07-02
        • 2011-06-30
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多