数据成员"查询回调"不能是成员模板

Data member 'queryCallback' cannot be a member template

本文关键字:成员 不能 查询 回调 数据成员      更新时间:2023-10-16

我在编译以下成员定义时遇到问题:

template<typename... A>
std::tuple<std::string, std::function<void(A...)> > queryCallback;

错误如标题所示:

/databasedispatcher.h:14: error: data member 'queryCallback' cannot be a member template

我意识到我不能为非方法/函数的成员使用模板定义。考虑到这一点,在这种情况下我如何使用<A...> ?

谢谢。

根据经验,您需要将其定义为模板别名:

template<typename... A>
using queryCallback = std::tuple<std::string, std::function<void(A...)>>;

代码例子:

#include <tuple>
#include <iostream>
#include <string>
#include <functional>
template<typename... A>
using queryCallback = std::tuple<std::string, std::function<void(A...)>>;
int main()
{
  auto foo = [](int a, int b) { std::cout << a << " + " << b << " = " << a + b << std::endl; };
  queryCallback<int, int> A("foo", foo);
  std::cout << std::get<0>(A) << std::endl;
  std::get<1>(A)(2, 2);
  return 0;
}
输出:

foo

2 + 2 = 4

使用别名模板:

template<typename... B>
struct T
{
    template<typename... A> using QueryCallbackType = std::tuple<std::string, std::function<void(A...)>>;
    QueryCallbackType<B...> query_callback;
};