2016-07-27 85 views
2

動機爲this example使用std::less/std::greater。 是否可以使用std::minstd::max作爲模板比較器?std :: min/std :: max作爲模板比較器

以下示例引發錯誤:

error: type/value mismatch at argument 1 in template parameter list for 'template<class C> class Test'

#include <functional> 
#include <algorithm> 

template <typename C> 
class Test 
{ 
public: 
    int compare(int x, int y) 
    { 
     return C()(x, y); 
    } 
}; 

int main() { 
    Test<std::min<int>> foo; 
    Test<std::max<int>> bar; 
    foo.compare(1, 2); 
    bar.compare(1, 2); 
} 

回答

2

std::minstd::max是函數模板。如果你想使用它們作爲模板參數,你需要將它們聲明爲non-type template parameter,如函數指針:

template <const int& (*C)(const int&, const int&)> 
class Test 
{ 
public: 
    int compare(int x, int y) 
    { 
     return C(x, y); 
     //  ~~ Note no() here 
    } 
}; 
+0

所以有兩個模板參數,'template ?' – pyCthon

+1

@pyCthon是的,你可以。並將它們用作'Test > foo;'。 – songyuanyao

2

std::min<int>std::max<int>不類型。它們是功能。

Test<std::min<int>> 

Test模板預計其參數爲一個類(或更確切地說,一個類型),而不是一個函數。該模板聲明爲:

template <typename C> class Test 

typename表示模板參數是類/類型。

此外,該模板聲明一個名爲「比較」的方法。 main()嘗試調用稱爲「運行」的方法。那將是另一個問題。

+0

謝謝,我固定的函數名,還爲什麼會'的std :: less'工作,而不是'性病:: min'? – pyCthon

+1

@pyCthon std :: less'是一個'struct','std :: min'是一個函數 – Rakete1111

1

它的std :: min和std :: max函數不是類。可能使用仿函數類模板來包裝的std ::最小/最大功能也是一個更好的選擇,如下面的代碼:

#include <iostream> 
#include <functional> 
#include <algorithm> 

template <typename C> 
class Test 
{ 
public: 
    int compare(int x, int y) 
    { 
     return C()(x, y); 
    } 
}; 

template<typename T> 
class MinComp { 
public: 
    T operator()(T x, T y) { 
     return std::min<T>(x,y); 
    } 
}; 

int main() { 
    Test<MinComp<int>> foo; 
    std::cout<<foo.compare(5, 2); 

}