【发布时间】:2021-06-09 18:45:31
【问题描述】:
我有以下用例。
Messages.h
template <typename Message>
Message deserialize(std::string const &buf);
template <>
RequestHeader deserialize(std::string const &buf);
template <typename Message>
std::string serialize(Message const &msg);
#include "Messages.inl"
Messages.inl
template <typename Message>
Message deserialize(std::string const &buf, bool partial)
{
Message msg;
size_t bufSize = buf.length();
size_t msgSize = sizeof msg;
if (msgSize > bufSize)
throw std::underflow_error("Message size exceeds buffer size.");
if (msgSize < bufSize && !partial)
throw std::overflow_error("Buffer size exceeds message size.");
std::memcpy(&msg, &buf[0], (msgSize < bufSize) ? msgSize : bufSize);
return msg;
}
template <typename Message>
Message deserialize(std::string const &buf)
{
return deserialize<Message>(buf, false);
}
template <typename Message>
std::string serialize(Message const &msg)
{
auto ptr = reinterpret_cast<const char*>(&msg);
return std::string(ptr, ptr + sizeof msg);
}
Messages.cpp
#include "Messages.h"
template <>
RequestHeader deserialize(std::string const &buf)
{
return deserialize<RequestHeader>(buf, true);
}
此代码的“问题”是带有签名的模板
Message deserialize(std::string const &buf, bool partial)
可通过任何使用Messages.h 的单元在标题中包含*.inl 文件来公开获得。
但是,它只是泛化反序列化的内部助手,不应公开提供。如果它是常规函数而不是模板,我会将其标记为静态,以便仅在翻译单元中可见。但这似乎对内联文件中的模板没有影响。
我将如何从头文件中隐藏这个模板并仍然从中派生其他模板函数和特化?有没有可能?
【问题讨论】:
-
目前尚不清楚助手是否在一个文件中使用,仅(这是
static的建议)。如果是这种情况,那么只需在该文件中定义帮助程序。 -
helper目前只在
Messages.inl中使用,它又包含在Messages.h中,这是我不想暴露helper函数的外部接口。 -
C++20 通过模块使这成为可能:帮助器可以不用于名称查找,即使它们(必须)可用于实例化。
-
@DavisHerring 感谢您的评论,我也添加了关于 C++20 模块的评论。您知道能够处理 C++ 模块的在线编译器吗?
-
@2b-t:编译器资源管理器有几个(处于不同的完成阶段)。
标签: c++ templates static c++17