enable class's member depending on template

天大地大妈咪最大 提交于 2019-12-03 12:30:19

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;
};

and then use m._projection etc.

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.

AFAIK, this is not possible with a simple SFINAE inside the class template. You can, of course, have the type of the member dependent on a compile-time condition, i.e. via std::conditional, but not eliminate the member entirely.

What you can do, of course, is use another class template, such as

template<bool Condition, typename T> struct Has { T value; };
template<typename T> struct Has<false,T> {};

and declare a member (or base) of this type and access the object via Has<>::value:

typename<Condition>
class foo
{
  Has<Condition, double> x;   // use x.value (only if Condition==true)
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!