Rob*_*est 5 c++ templates pimpl-idiom wrapper variadic-templates
我正在编写一个库和一个客户端应用程序。在库中,我正在尝试围绕另一个静态链接的第三方库(特别是spdlog)编写一个包装器,并尝试使用 pImpl 习惯用法将它完全隐藏在客户端应用程序之外。问题是第三方库使用了可变参数模板函数,所以我也需要在我的库中使用。
我对包装器的第一次尝试非常简单和直接,但后来我在我的客户端应用程序中收到“没有这样的文件或目录”错误,因为第三方标头包含在我的库标头中。
我接下来尝试创建一个 pImpl 类并编译它,但在客户端我再次收到“未定义引用”链接器错误。
将实现的源代码拉到我的包装器的标题中,让我回到最初的“没有这样的文件”问题。对此进行研究后,我开始认为不可能围绕可变参数模板制作包装器,但我不确定。这是我第一次尝试制作可变参数函数/模板。
这是我的项目目前的情况:
为了简洁和清晰,几乎所有的命名空间、函数名称、标题等都已被编辑(或删除)。
#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;
}
Run Code Online (Sandbox Code Playgroud)
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. */
Run Code Online (Sandbox Code Playgroud)
#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...);
}
Run Code Online (Sandbox Code Playgroud)
#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.
}
}
Run Code Online (Sandbox Code Playgroud)
如上所述,我只希望我的库的客户端能够包含标头<logger.h>,而不需要配置他们的项目来查找和处理我的库的所有依赖项,但由于我目前正在使用使用的第三方工具可变参数模板鉴于模板的“不是真正的功能”性质,我没有看到任何可以向我的客户隐藏它的方法。
您可以在头文件中进行类型擦除,并在 impl 源文件中处理类型擦除后的类型。
// log.hpp
#pragma once
#include <any>
#include <vector>
#include <utility>
struct Log {
Log(int a);
~Log();
template <class... A>
void log(A&&... a) {
log_impl({std::any(std::forward<A>(a))...});
}
private:
void log_impl(std::vector<std::any> v);
struct Impl;
Impl* impl_;
};
// log.cpp
#include "log.hpp"
#include <iostream>
#include <boost/mp11.hpp>
struct Log::Impl {
int a;
};
void Log::log_impl(std::vector<std::any> v) {
std::cout << impl_->a << " ";
for (auto&& i : v) {
bool b = false;
using namespace boost::mp11;
mp_for_each<mp_list<int, const char*, double>>(
[&](auto t) {
if (!b) {
try {
std::cout << std::any_cast<decltype(t)>(i) << " ";
b = true;
} catch (std::bad_any_cast&) {
}
}
});
if (!b) {
std::cout << "UNKNOWN ";
}
}
std::cout << std::endl;
}
Log::Log(int a) : impl_(new Log::Impl{a}) {}
Log::~Log() { delete impl_; }
// client.cpp
#include "log.hpp"
struct A {
char a;
};
std::ostream& operator<<(std::ostream& os, const A& a) { os << a.a; }
int main() {
Log a(555);
a.log(11, "222"); // output: 555 11 222
a.log(A{'a'}, 3.3); // output: 555 UNKNOWN 3.3
}
Run Code Online (Sandbox Code Playgroud)
// log.hpp
#pragma once
#include <vector>
#include <utility>
#include <functional>
#include <iostream>
struct Log {
Log(int a);
~Log();
template <class... A>
void log(A&&... a) {
log_impl({[&a](std::ostream& os) { os << std::forward<A>(a); }...});
}
private:
void log_impl(std::vector<std::function<void(std::ostream&)>> v);
struct Impl;
Impl* impl_;
};
// log.cpp
#include "log.hpp"
#include <iostream>
struct Log::Impl {
int a;
};
void Log::log_impl(std::vector<std::function<void(std::ostream&)>> v) {
std::cout << impl_->a;
for (auto&& i : v) {
std::cout << ' ';
i(std::cout);
}
std::cout << std::endl;
}
Log::Log(int a) : impl_(new Log::Impl{a}) {}
Log::~Log() { delete impl_; }
// client.cpp
#include "log.hpp"
struct A {
char a;
};
std::ostream& operator<<(std::ostream& os, const A& a) { os << a.a; }
int main() {
Log a(555);
a.log(11, "222"); // output: 555 11 222
a.log(A{'a'}, 3.3); // output: 555 a 3.3
}
Run Code Online (Sandbox Code Playgroud)
这是一个为类型擦除类型提供fmt 自定义格式化程序的示例。
namespace {
struct erased_type : std::vector<std::any> {};
} // namespace
namespace fmt {
template <>
struct formatter<erased_type> {
template <typename ParseContext>
constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const erased_type &v, FormatContext &ctx) {
auto ctx_itr = ctx.begin();
for (auto&& i : v) {
bool b = false;
using namespace boost::mp11;
mp_for_each<mp_list<int, const char*, double>>([&](auto t) {
if (!b) {
try {
format_to(ctx_itr, " {}", std::any_cast<decltype(t)>(i));
b = true;
ctx_itr++;
} catch (std::bad_any_cast&) {
}
}
});
if (!b) {
format_to(ctx_itr++, " UNKNOWN");
}
}
return ctx_itr;
}
};
}
void Log::log_impl(std::vector<std::any> v) {
spdlog::info("{} {}", impl_->a, erased_type{std::move(v)});
}
Run Code Online (Sandbox Code Playgroud)