簡體   English   中英

在C ++中如何使用模板函數作為std :: for_each中的第3個參數?

[英]In C++ how can I use a template function as the 3rd parameter in std::for_each?

我正在嘗試使用std :: for_each來輸出向量的內容,這些向量可能包含不同的類型。 所以我寫了一個通用輸出函數,如下所示:

template<typename T> void output(const T& val)
{
    cout << val << endl;
}

我想用它:

std::for_each(vec_out.begin(), vec_out.end(), output);

但是編譯器在for_each語句中抱怨“無法推斷出模板參數”。 還抱怨“函數模板不能成為另一個函數模板的參數”。

這不可能嗎? 我原以為編譯器會知道vec_o​​ut(它的向量)的類型,所以應該實例化函數“output(const double&val)”?

如果這不起作用,如何在不編寫手動循環的情況下獲得類似的STL功能?

我對C ++很新,還在學習繩索:-)

嘗試:

std::for_each(vec_out.begin(), vec_out.end(), output<T>);

其中vec_out是類型為T的容器( vector )。

注意: for_each算法需要一個一元仿函數用於其最后一個參數。 有關使用仿函數的示例,請參閱鏈接。

您必須傳遞模板的實例化。 如果你的向量是整數向量,那就像output<int>

例如:

template<typename T> void output(const T& val)
{
    cout << val << endl;
}



void main(int argc,char *argv[])
{
    std::vector<int> vec_out;
    std::for_each(vec_out.begin(), vec_out.end(), output<int>);
}   

我只想添加正確的答案:如果你將模板函數包裝在一個函數對象(aka functor)中,編譯器可以推斷出類型:

struct OutputFunctor
{
  template <typename T>
  void operator()(const T& val) const { output(val); }
};

void test()
{
  std::vector<int> ints;
  std::vector<float> floats;

  std::for_each(ints.begin(), ints.end(), OutputFunctor());
  std::for_each(floats.begin(), floats.end(), OutputFunctor());
}

暫無
暫無

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

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