c++ - 特质专精

标签 c++ typetraits

我想在特征特化中定义一个存储类型。但是对于某些情况,我没有任何可以真正定义的东西,即某些特化没有存储类型。当然使用 void 类型不是办法,但我正在寻找类似的东西。我不确定我是否在朝着正确的方向前进——一种方法可能是只使用 bool 类型,因为它占用的空间最少。克服这个问题的正确/好的方法是什么。我不确定是否有人问过这样的问题。我不知道要搜索什么!

template<typename T>
struct Traits
{
}     

template<>
struct Traits<TypeA>
{
    typedef std::vector<double> storage;
}     

template<>
struct Traits<TypeB>
{
    typedef std::vector<string> storage;
}

 template<>
struct Traits<TypeC>
{
    //I do not want to specify a storage type here. More like it does not exist. 
    //So what is the correct way to define such a type
    typedef ??void?? storage;
}


int main()
{
    typename Traits<TypeA>::storage myType;
    /*
    do domething
    */
}

最佳答案

只需省略 storage没有意义的 typedef:

template<>
struct Traits<TypeC>
{
};

现在使用 Traits<TypeC>::storage成为错误,因为它没有命名类型。

其他说明:

  • struct 后需要分号声明/定义。
  • 你的 Traits模板(不是特化)应该没有主体,除非有一个对每种类型都有意义的主体。即应该是template <typename> struct Traits; .这将导致它与一个没有意义的模板参数一起使用,从而导致错误。

关于c++ - 特质专精,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26853430/

相关文章:

c++ - 我们可以在 C++17 中检测到 "trivial relocatability"吗?

c++ - 如果 std::vector 作为 T::Zero 存在,如何生成代码以使用自定义零值初始化 std::vector?

c++ - 平凡可移动但不可平凡复制

c++ - 混合调试和发布库 : Windows vs Linux, 静态与共享

c++ - 错误 : expected unqualified-id before '{' token

c++ - 使用 std::array 与数组传递对象数组

c++ - 将 "wstring"转换为 "const UInt8 *"

C++智能指针

c++ - 如何在类范围内定义/专门化 type_trait?

c++ - 为什么 std::is_aggregate<T> 是聚合?