:C :仅揭示专业模板

:C++: Exposing specialized templates only

本文关键字:      更新时间:2023-10-16

我想使用以下类创建自己的序列化。我想拥有一般保护<<操作员并仅发布一些完全键入的专业:

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
}

只是将答案从@drewdormann评论中移出 - 我应该将专业模板写为:

template <> TBinaryOut & operator << (const uint8_t& i);

编辑:这不起作用。汇编还可以,但是我在链接过程中尚未解决此专业。

也要感谢@LiLiscent的另一个优雅解决方案(以下(。

相关文章:
  • 没有找到相关文章