簡體   English   中英

使用模板確定要調用的函數

[英]Using Templates to determine function to call

假設一個類可以使用以下數據類型來回傳遞數據:

std::vector<complex> // where "complex" is a struct 
and
std::vector DOUBLE or INT or FLOAT or STRING

如果用戶經過std::vector<double>則意味着已經進行了計算,因此只需完成一個很小的過程即可。 但是,如果用戶通過std::vector<complex>則意味着必須執行計算。

在課堂上,我可以執行以下操作:

class Foo {

  template<typename T>
  Foo(T begin, T end)
  {
      this->transform(begin, end);
  }
  template<typename T>
  void transform(T begin, T end)
  {
       std::cout << "This has been called";

  }
};

但是,這仍然必須使我不得不擁有一種特定類型的data member ,並始終假設他們正在這樣做。

例如,是否有可能在2種不同情況下覆蓋函數transform ,並讓構造函數根據傳遞給構造函數的數據類型來決定要調用的方法。

它會像這樣工作:

int main()
{
    std::vector<double> vals = {1,1,1,1,1,1,1,1};

    Foo(std::begin(vals), std::end(vals)); // this will call the method that handles dbls

    std::vector<complex> vals = {};

    Foo(std::begin(vals), std::end(vals)); // This will call the method that handles complex numbers

}

我希望這是有道理的

這可以通過模板專門化解決。

考慮以下功能:

template<typename T>
void Foo(T arg)
{
    std::cout << "General" << std::endl;
}

現在,我們可以將此功能專用於char類型,這意味着為這些類型提供另一種實現:

template<>
void Foo(char arg)
{
    std::cout << arg << std::endl;
}

注意,在這種情況下可以省略template<>

如果我們現在這樣調用函數:

Foo(1);
Foo('a');

輸出將是:

General
a

一種方法是標記分派(我在這里使用struct X而不是complex ):

#include <iostream>
#include <vector>
#include <iterator>

struct X {};

struct Foo {
  template<typename T>
  Foo(T begin, T end)
  {
      transform(begin, end, typename std::iterator_traits<T>::value_type());
  }
  template<typename T, typename U>
  void transform(T begin, T end, U) // third parameter is unused and serves as a tag
  {
    std::cout << "floating point\n";
  }

  template<typename T>
  void transform(T begin, T end, X) // same here
  {
     std::cout << "X\n";
  }
};

int main()
{
    std::vector<double> v1 = {1,1,1,1,1,1,1,1};

    Foo(std::begin(v1), std::end(v1)); // floating point

    std::vector<X> v2 = {};

    Foo(std::begin(v2), std::end(v2));  // X
}

暫無
暫無

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

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