【发布时间】:2019-06-09 18:13:20
【问题描述】:
总结
我正在编写一个库和一个客户端应用程序。在库中,我尝试围绕另一个静态链接的第三方库(特别是spdlog)编写包装器,并尝试使用 pImpl 习惯用法将其完全隐藏在客户端应用程序中。问题是第三方库使用了可变参数模板函数,所以我的库中也需要。
背景
我对包装器的第一次尝试非常简单直接,但随后我的客户端应用程序中出现“没有这样的文件或目录”错误,因为第三方标头包含在我的库的标头中。
接下来我尝试创建一个 pImpl 类并对其进行编译,但在客户端中我再次收到“未定义引用”链接器错误。
将实现的源代码拉到我的包装器的标头中,让我回到最初的“没有这样的文件”问题。在研究了这个之后,我开始认为围绕可变参数模板制作包装器是不可能的,但我不确定。这是我第一次尝试制作可变参数函数/模板。
示例代码
这是我的项目目前的情况:
为了简洁明了,几乎所有命名空间、函数名称、标题等都已被编辑(或删除)。
客户端应用程序 - sandbox.cpp
#include "sandbox.h"
#include <logger.h> // <-- This is all I want clients to see.
int Sandbox::run() {
LOG_INFO("Hello World!"); // My library is providing this.
LOG_INFO("Hello {}", "indeed!"); // And, this variable input function.
return 0;
}
我的图书馆 - logger.h
class LoggerImp; // Forward declaration of implementation.
class LIB_EXPORT Logger {
public:
/* Constructors, destructor, etc. */
template <typename... Args>
void info(const char * fmt, Args &... args);
void info(const char * msg) { this->info("{}", msg); }
/* Other logging functions: trace, error, etc. */
private:
LoggerImp * _imp;
};
static Logger coreLogger("Core");
static Logger clientLogger("App");
#define LOG_INFO(args...) clientLogger.info(args)
/* Other such convenience definitions. */
我的图书馆 - logger.cpp
#include "logger.h"
#include "loggerimp.h"
Logger::Logger(std::string name) { _imp = new LoggerImp(name, this); }
Logger::~Logger() { delete _imp; }
template <typename... Args>
void Logger::info(const char * fmt, Args &... args) {
_imp->info(fmt, args...);
}
我的图书馆 - loggerimp.h
#include "logger.h"
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
class LoggerImp {
public:
explicit LoggerImp(string name, Logger * pubInterface) :
_pubInterface(pubInterface) { // Back pointer.
_sink = make_shared<spdlog::sinks::stdout_color_sink_mt>();
_logger = make_shared<spdlog::logger>(name, _sink);
spdlog::initialize_logger(_logger);
// The above three lines create the actual logging object
// that my library is wrapping and hiding from its clients.
}
template <typename... Args>
inline void info(const char * fmt, const Args &... args) {
_logger->info(fmt, args...); // Third-party logging function.
}
}
预期结果
如上所述,我只希望我的库的客户端能够包含像 <logger.h> 这样的标头,并且不需要配置他们的项目来查找和处理我的库的所有依赖项,但是因为我目前正在使用使用可变参数模板的第三方工具鉴于模板的“不是真正的功能”性质,我没有看到任何可以向客户隐藏它的方法。
【问题讨论】:
-
您在
.cpp文件中有Logger::info的定义。您是否知道所有模板定义都需要在编译时可用?这就是为什么您通常将它们放在标题中的原因。这包括您的第三方依赖项中的那些。 -
pImpl 和模板不混用,pimpl 隐藏所有实现细节,模板在用户端根据模板参数生成代码,想知道实现。我会使用 c++20 格式库将所有内容转换为单个字符串,然后转发到实现。
-
感谢您的回复。 @super,我现在。在过去的几天里,我读了很多关于模板的内容。 @JVApen 格式化库还不是 C++ 标准的正式一部分,对吧?另外,我看不出使用 fmtlib 对我有什么帮助。它已经在 spdlog 中,而且它也是使用可变参数模板构建的,所以它不会给我带来我已经遇到的问题吗? ... 是否有共识在客户端使用模板时无法隐藏第三方库?我是否别无选择,只能将额外的依赖暴露给我的客户,或者推出我自己的解决方案? :-(
-
它被正式投票加入了C++20,还没有正式发布,我是对的。 (也许他们仍然需要做措辞)有一个 github 存储库,其中包含提案作者的完整工作版本
-
由于 format 使用类似的语法,甚至是相同的语法,您可以通过 variadic 和 format 将其转换为单个参数(字符串),您可以将其转发给您的 impl。
标签: c++ templates wrapper variadic-templates pimpl-idiom