函数指针作为模板参数

时间:2018-10-03 23:20:24

标签: c++ templates lambda

我在“ concurrent_sorted_list.h”中具有以下类模板:

template <typename T, int (* Compare)(T,T)>
class ConcurrentSortedList{
 ....
}

在我的main.cpp中:

int (*intCompare)(int, int) = [](int a, int b) -> int {
  if (a < b)
    return -1;
  else if (a == b)
  return 0;
  return 1;
};

ConcurrentSortedList<int, decltype(intCompare)> c;
c.Add(5);
c.Add(6);
assert(c.Size() == 2);

但是我收到以下编译器错误: expected a constant of type ‘int (*)(T, T)’, got ‘int (*)(int, int)’

如果我将decltype(intCompare)更改为intCompare,则会收到以下编译器错误: the value of ‘intCompare’ is not usable in a constant expression, ‘intCompare’ was not declared ‘constexpr’, ‘intCompare’ is not a valid template argument for type ‘int (*)(int, int)’, it must be the address of a function with external linkage

1 个答案:

答案 0 :(得分:0)

您的代码中有太多技巧。您只需要:

type weight = int
type height = int 
type colours = Red | Black | Orange | White
type cat = Cat of weight * height * colours list

let cat1 = Cat (14, 14, [Red; Black])
let cat2 = Cat (15, 20, [Black; White])
let cat3 = Cat (13, 15, [Red; White])
let cats =  [cat1; cat2; cat3]

然后,正如其他人所说的那样:

int intCompare(int a, int b)
{
    if (a < b)
        return -1;
    if (a == b)
        return 0;
    return 1;
};

Live demo

ConcurrentSortedList<int, intCompare> c; 也可以使用,FWIW。