簡體   English   中英

C++ 通過多個函數傳遞模板參數

[英]C++ Pass template argument through multiple functions

考慮這些代碼行。 當我嘗試編譯時,編譯器會顯示錯誤,例如'a' is not a member of 'DataType1' 我了解編譯器如何將這些視為錯誤,但是有什么方法可以避免這種方法或其他有效的方法嗎?

struct DataType1 { public: int x; };
struct DataType2 { public: int a; };

template <class E>
bool job2(E* newData, const int i){
  int something = 2;  
  if (i == 1) newData->x = something;
  if (i == 2) newData->a = something;
}

template <class E>
bool job1(List<E>* dataBase){
  E* newData = new E;
  job2(newData, 1);
  dataBase->push_back(newData);
}

template <class E>
int main(){
  List<DataType1>* dataBase = new List<DataType>;
  job1(dataBase);
}

如果你手頭有 C++17,你可以寫:

template <class E>
bool job2(E* newData){
  int something = 2;  
  if constexpr (std::is_same_v<E, DataType1>) 
     newData->x = something;
  else 
     newData->a = something;
}

並一起丟棄i (如果您僅使用它來區分類型)。

Othwerwise,什么反對簡單地超載你的 function?

bool job2(DataType1* newData){
  commonOperation();
  newData->x = something;
}

bool job2(DataType2* newData){
  commonOperation();
  newData->a = something;
}

其中commonOperation是函數的所有共同點。

暫無
暫無

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

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