如何添加依赖于类本身的模板成员变量

How to add a template member variable that depends on the class itself

本文关键字:变量 成员 何添加 添加 依赖于      更新时间:2023-10-16

我有一个模板类,需要传递一个可调用的对象来处理错误。 可调用对象必须重载void operator()(const boost::system::error_code&),并且其类型作为模板参数传递以使类更通用(例如接受lambdas(。

类看起来像这样

template <typename AsyncStream,
typename ErrorHandler,
typename = std::enable_if_t<...>>
struct basic_api {
...
private:
AsyncStream sock_;
ErrorHandler error_handler_;
};

现在,我想在另一个重载void operator()(const boost::system::error_code&)的类中创建此类的实例

测试治具示例:

struct BasicApiTest : ::testing::Test {
void operator()(const boost::system::error_code& err) {
// handler errors
}
std::shared_ptr<basic_api<tikpp::tests::fakes::socket, ???>> api;
};

我试图通过创建一个具有错误处理函数重载的附加类来解决这个问题,然后从中派生,如下所示:

struct error_handler {
void operator()(const boost::system::error_code& err)
// handle errors
}
};
struct BasicApiTest : error_handler, ::testing::Test {
using socket_type  = tikpp::tests::fakes::socket;
using handler_type = error_handler;
using api_type     = tikpp::basic_api<socket_type, handler_type>;
BasicApiTest() : api{...} {}
std::shared_ptr<api_type> api;
};

但是这个解决方案有很多局限性。

这在C++中可行吗,还是我应该找到另一种方法来传递错误处理程序?

首先,您的要求很难理解。这听起来像是一个所谓的XY问题。请参阅此处的说明。

问题可能不是,如何使用模板或特殊语法。真正的问题也许是不同的。我认为,你想实现一些可以通过类层次结构轻松降低的东西。基类中使用纯虚函数,派生类中使用覆盖函数。

但是你在某处提到你认为开销太大了。

因此,我假设您的问题是关于静态多态性的。这通常可以通过CRTP"奇怪的重复模板模式"来解决。在这里,您有一个模板化的基类和一个派生类,后者派生自基。

请从阅读这里开始。

我希望我理解你的问题。如果没有,请发表评论,我将删除答案。