问题描述
我已经知道您可以使用std::enable_if
I already know that you can enable (or not) a class's method using std::enable_if
例如:
template<size_t D, size_t E>
class Field
{
...
size_t offset(const std::array<float,D>& p) const
{
...
}
template<typename TT = size_t>
typename std::enable_if<D!=E, TT>::type
offset(const std::array<float,E>& p) const
{
return offset(_projection(p));
}
...
};
这有助于在特定情况下无法调用无效的函数,并消除重载错误……对我来说,这非常好!
This helps not being able to call function that are invalid in a specific case as well as removing overloading errors ... which, to me, is very nice !
我想走得更远,只有在需要时,让班上的一些成员才在场.这样,如果我尝试使用否则将不会启动的对象,就会出现错误
I'd like to go further and make some of my class's members being present only if the are needed. That way I would get an error if I try to use an objected which would have otherwise not been initiated
我试图做
template<size_t D, size_t E>
class Field
{
...
template<typename TT = projectionFunc>
typename std::enable_if<D!=E, TT>::type _projection;
}
但是编译器告诉我:
erreur: data member ‘_projection’ cannot be a member template
有什么办法可以实现我想要的吗?
Is there any way to achieve what I want ?
推荐答案
将数据成员保留在一个单独的类中,然后可以根据需要对其进行专门化.
Hold the data members in a separate class that you can then specialize as needed.
template<size_t D, size_t E>
class Field {
template<size_t, size_t> struct Field_Members {
int _projection;
};
template<size_t V> struct Field_Members<V, V> { };
Field_Members<D, E> m;
};
,然后使用m._projection
等.
Field_Members
不必是嵌套的类模板;您可以根据需要将其移到外面.也可以从中继承Field
,但是它将成为一个从属基础,并且您必须编写this->_projection
,因此它不会节省太多键入内容.
Field_Members
doesn't have to be a nested class template; you can move it outside if desired. It is also possible to have Field
inherit from it, but then it'd be a dependent base, and you'd have to write this->_projection
, so it doesn't save much typing.
这篇关于根据模板启用类的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!