std :: min / std :: max作为模板比较器

时间:2016-07-27 02:15:22

标签: c++ templates c++14

this example使用std::less/std::greater的动机。 是否可以使用std::minstd::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);
}

3 个答案:

答案 0 :(得分:2)

std::min<int>std::max<int>不是类型。它们是功能。

Test<std::min<int>> 

Test模板期望其参数是类(或者更确切地说是类型),而不是函数。模板声明为:

template <typename C> class Test

typename表示模板参数是类/类型。

此外,模板声明了一个名为&#34; compare&#34;的方法。 main()尝试调用名为&#34; run&#34;的方法。那将是另一个问题。

答案 1 :(得分:2)

注意std::minstd::max是功能模板。如果要将它们用作模板参数,则需要将它们声明为non-type template parameter,例如函数指针:

  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      <t:RequestServerVersion Version="Exchange2013_SP1" />
    </soap:Header>
    <soap:Body>
      <m:Subscribe>
        <m:PullSubscriptionRequest SubscribeToAllFolders="true">
          <t:EventTypes>
            <t:EventType>CopiedEvent</t:EventType>
            <t:EventType>CreatedEvent</t:EventType>
            <t:EventType>DeletedEvent</t:EventType>
            <t:EventType>ModifiedEvent</t:EventType>
            <t:EventType>MovedEvent</t:EventType>
            <t:EventType>NewMailEvent</t:EventType>
          </t:EventTypes>
          <t:Timeout>5</t:Timeout>
        </m:PullSubscriptionRequest>
      </m:Subscribe>
    </soap:Body>
  </soap:Envelope>

答案 2 :(得分:1)

std :: min和std :: max是函数而不是类。可能使用Functor类模板来包装std :: min / 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);

}
相关问题