簡體   English   中英

C++ 獲取模板參數的返回類型

[英]C++ get return type for template argument

我有

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派生返回類型?

如何從 DistanceFunc 為 DistanceType 派生返回類型?

另一種解決方案是使用模板專業化。

您可以將C聲明為接收typename名,而無需定義它

template <typename>
class C;

然后你可以定義一個 C 的特化接收(指向)function 類型如下

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;
};

如您所見,function 類型被解析為返回類型,而 arguments 的類型。 現在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 object

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

如何從 DistanceFunc 為 DistanceType 派生返回類型?

要看。 如何稱為DistanceFunc類型的 function ?

假設用int調用,您可以嘗試如下

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

如果您有從DistanceFunc接收的類型,則使用decltype()std::declval()您可以模擬對 function 的調用並獲得結果類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM