我想在特征特化中定义一个存储类型。但是对于某些情况,我没有任何可以真正定义的东西,即某些特化没有存储类型。当然使用 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/