2016-07-27 5 views
2

this exampleを動機とするstd::less/std::greaterを使用しています。 std::minまたはstd::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); 
} 
std::min<int>

答えて

2

注:おそらくのstd ::最小/最大機能をラップするためのFunctorクラステンプレートを使用した場合も、以下のコードのように、より良いオプションです。あなたがテンプレートパラメータとしてそれらを使用する場合は、そのような関数ポインタとして、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

これは2つのテンプレートパラメータ' template ? ' – pyCthon

+1

@pyCthonはい、できます。そしてそれらを 'Test > foo;'として使ってください。 – songyuanyao

2

std::max<int>は、型ではありません。それらは関数です。

Test<std::min<int>> 

Testテンプレートは、そのパラメータがクラス(または、むしろ、種類)、機能しないことを期待。テンプレートは次のように宣言されています

template <typename C> class Test 

typenameテンプレートパラメータは、クラス/タイプであることを意味しています。

さらに、テンプレートは "compare"というメソッドを宣言します。 main()は "run"というメソッドを呼び出そうとします。それは別の問題だろう。

+0

感謝し、私はなぜだろう 'のstd :: less'の仕事も、関数名を固定していない'のstd ::分 '? – pyCthon

+1

@pyCthon 'std :: less'は' struct'です、 'std :: min'は関数です – Rakete1111

1

std :: minとstd :: maxはクラスではない関数です。 std::minstd::maxは関数テンプレートです

#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); 

} 
関連する問題