如何添加依赖于类本身的模板成员变量
How to add a template member variable that depends on the class itself
我有一个模板类,需要传递一个可调用的对象来处理错误。 可调用对象必须重载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"奇怪的重复模板模式"来解决。在这里,您有一个模板化的基类和一个派生类,后者派生自基。
请从阅读这里开始。
我希望我理解你的问题。如果没有,请发表评论,我将删除答案。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- C++预处理会生成变量成员、资源库和映射
- 局部堆栈变量成员的返回值优化
- Google Mock:在目标类的构造函数中实例化的模拟私有变量成员
- 使用指向结构变量成员的指针访问该结构的成员的地址
- 如果派生类仅包含自动变量成员,是否有必要具有虚拟驱动器
- 线程安全性和静态变量/成员功能
- "static const char array"可以在 C 语言上包含变量成员吗
- 仅用于内部目的的类的所有变量/成员的技术术语是什么
- 如何强制转换变量成员以将其作为函数的引用参数传递
- 类中未声明变量成员函数
- 在 main 中初始化类的 "static const" 类型变量成员的更好方法
- c++模板类静态const变量成员作为映射键给出未定义引用
- 在类中初始化结构变量成员会导致分割错误
- 在c++中建模变量成员类型
- 模板私有静态变量成员的未定义符号
- 不能访问公共静态变量成员
- 常量变量成员在C++有什么用?
- g++ 4.8.2坚持简单变量成员是数组