簡體   English   中英

推導出依賴於模板函數類型的變量類型

[英]deduce type of variable dependent on template function type

我有一個模板功能:

// Overloaded functions, Class1In, Class1Out, Class2In and Class2Out
// are defined in the code.  
Class1Out Init(Class1In one) { ... }
Class2Out Init(Class2In two) { ... }

template <class A>
void f(A a, int retry_count) {
  B b = Init(a); // How to express B?
}

問題是我怎么表達B 我嘗試了以下內容,但是當我調用f時,編譯器無法推斷出B錯誤

template <class A, class B>
void f(A a, int retry_count) {
  B b = Init(a); // compiler error: Cannot deduce template parameter B
}

我無法真正在f之外調用Init ,因為函數通過調用自身重試,並且每次調用它時都需要創建b的新實例。

我怎么做到這一點?

你可以使用auto ,但一般來說你可以使用這個技巧來確定類型B

using outType = decltype(Init(std::declval<A&>()));

對於您的特定情況,您還可以使用更簡單的格式(感謝用戶max66):

using outType = decltype(Init(a));

這允許您知道b的類型而無需實例化它。

如果您需要實例化b那么您也可以嘗試

auto b = Init(a);
using outType = decltype(b);

在下面的代碼中,我展示了添加一些樣板代碼的用法。

#include <type_traits>

class Class1Out{};
class Class2Out{};

class Class1In{};
class Class2In{};


Class1Out Init(Class1In one);
Class2Out Init(Class2In two);

template <class A>
void f(A a, int retry_count) {

  using outType = decltype(Init(std::declval<A&>()));
  outType b = Init(a); // How to express B?
}


int main(){

    Class1In in1{};
    Class2In in2{};

    f(in1, 4);
    f(in2, 4);
}

有關std::declvaldecltype更多信息,請參閱: https std::declvalhttps://en.cppreference.com/w/cpp/language/decltype

暫無
暫無

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

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