【问题标题】:Is it possible to conditionally enable a non-const/const data member of a template class based on the constness of the template argument?是否可以根据模板参数的常量有条件地启用模板类的非常量/常量数据成员?
【发布时间】:2014-05-21 16:50:38
【问题描述】:

是否可以根据模板参数的 const 有条件地启用模板类的非 const/const 数据成员?或者也许有一些条件typedef?我考虑过将 std::enable_if 与 std::is_const 一起使用,但没有我可以使用的 std::is_not_const。

class A;

template <typename T>
class Test
{
    A& m_a; // If T != const.
    const A& m_a; // If T == const.
};

请注意,始终 T != A。

【问题讨论】:

    标签: c++ templates c++11


    【解决方案1】:

    是的,你可以使用std::conditional

    template <typename T>
    class Test
    {
        typename
        std::conditional<std::is_const<T>::value, const A&, A&>::type
        m_a;
    };
    

    【讨论】:

    • 也许这个问题也可以在这里回答,因为它是相关的。当有一些 T 时,即使在 T 实际上已经是非常量的情况下,使用 std::remove_const 获得“纯类型”会不会是错误的?
    • 没关系。 remove_const 将返回原始类型,如果它不是 const 限定的。但请注意,remove_const&lt;const T&amp;&gt; 给出了const T&amp;,因为它只删除了顶级限定符。
    【解决方案2】:

    是的,您可以这样做。 &lt;type_traits&gt; 标头有用于此目的的工具。

    template <typename T>
    class Test
    {
        typename std::conditional<
            std::is_const<T>::value,
            typename std::add_const<A>::type,
            typename std::remove_const<A>::type
        >::type m_a;
    };
    

    你甚至可以为此创建一个助手:

    //T is type to modify
    //S is source type to mimic
    struct mimic_const<T, S>
    {
    public:
        typedef typename std::conditional<
            std::is_const<S>::value,
            typename std::add_const<T>::type,
            typename std::remove_const<T>::type
        >::type type;
    };
    

    然后像这样使用它:

    template <typename T>
    class Test
    {
        typename mimic_const<A, T>::type m_a;
    };
    

    【讨论】:

    • add_const 在这里有点矫枉过正。
    • 好吧,const A 就够了。你也需要typename
    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多