указатель на функцию в качестве аргумента шаблона - PullRequest
0 голосов
/ 04 октября 2018

У меня есть следующий шаблон класса в "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 голосов
/ 04 октября 2018

В вашем коде слишком много трюков.Вам просто нужно:

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

И тогда, как говорили другие:

ConcurrentSortedList<int, intCompare> c;

Live демо

auto intCompare = [](int a, int b) -> int { ... также работает,FWIW.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...