我想使用以下类创建自己的序列化。我想拥有受一般保护的<
class TBinaryOut
{
public:
virtual void write(const char * ptr, size_t count) = 0;
protected:
template <typename T>
TBinaryOut & operator<< (const T& i)
{ write((const char *)(void *)&i, sizeof(T)); return *this; }
public:
template <unsigned int> TBinaryOut & operator << (const unsigned int& i);
template <int> TBinaryOut & operator << (const int& i);
template <uint8_t> TBinaryOut & operator << (const uint8_t& i);
template <int8_t> TBinaryOut & operator << (const int8_t& i);
};
不幸的是,这不起作用。如果我写
int A = 10;
Stream << A;
VS2013编译器始终尝试实例化通用受保护模板,因此会出现错误。我应该怎么做才能使其正常工作?
编辑:如果我写专业化为
template <> TBinaryOut & operator << (const unsigned int& i);
一切都可以编译,但是我得到了无法解决的链接器错误。
最佳答案
如果要对许多但不是全部类型使用模板实现,则可以使用特征来确定允许哪些类型。
#include <cstdint>
#include <cstdlib>
#include <type_traits>
template<class T>
struct is_exposed : public std::false_type{};
template<> struct is_exposed<int> : public std::true_type{};
template<> struct is_exposed<uint8_t> : public std::true_type{};
/* ... */
class TBinaryOut
{
public:
virtual void write(const char * ptr, size_t count);
public:
template <typename T, std::enable_if_t<is_exposed<T>::value, int> = 0>
TBinaryOut & operator<< (const T& i)
{ write((const char *)(void *)&i, sizeof(T)); return *this; }
};
int main() {
TBinaryOut t;
int A = 10;
t << A; // Ok, because int is explicitly exposed
short b = 20;
//t << b; // Error, because short is not exposed
}
关于c++ - :C++:仅公开专用模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48775362/