C++ C++;:无法从派生类访问受保护的成员

C++ C++;:无法从派生类访问受保护的成员,c++,c++11,C++,C++11,我有一个类MyVariable,它保存一个对象,并在必须修改该对象时执行一些额外的工作。现在,我想将其专门化为MyContainer,用于仅在修改容器本身(例如,通过push_back())而不是其元素时才执行此额外工作的容器对象 我的代码如下所示: template<typename T> class MyVariable { public: //read-only access if fine const T* operator->() const {ret

我有一个类
MyVariable
,它保存一个对象,并在必须修改该对象时执行一些额外的工作。现在,我想将其专门化为
MyContainer
,用于仅在修改容器本身(例如,通过
push_back()
)而不是其元素时才执行此额外工作的容器对象

我的代码如下所示:

template<typename T>
class MyVariable
{
public:
    //read-only access if fine
    const T* operator->() const {return(&this->_element);}
    const T& operator*()  const {return( this->_element);}

    //write acces via this function
    T& nonconst()
    {
        //...here is some more work intended...
        return(this->_element);
    }
protected:
    T _element;
};


template<typename T>
class MyContainer: public MyVariable<T>
{
public:
    template<typename Arg>
    auto nonconst_at(Arg&& arg) -> decltype(MyVariable<T>::_element.at(arg))
    {
        //here I want to avoid the work from MyVariable<T>::nonconst()
        return(this->_element.at(arg));   
    }
};


#include <vector>
int main()
{
    MyContainer<std::vector<float>> container;
    container.nonconst()={1,3,5,7};
    container.nonconst_at(1)=65;
}

这里发生了什么?

问题似乎确实与
decltype()
的使用有关-如果我明确声明
nonconst\u at()
以返回
T::value\u type&
,那么:

template<typename Arg>
typename T::value_type& nonconst_at(Arg&& arg)
只有一个警告(随着
-std=c++1y
消失),没有错误。我仍然需要
this->
,因为_元素是依赖基类的成员(谢谢)

编辑-其他解决方法: 由于您只对
T::at()
的返回值的类型感兴趣,因此可以使用
decltype
调用任意T,即使是空指针:

template<typename Arg>
auto nonconst_at(Arg&& arg) -> decltype(((T*)nullptr)->at(arg))
{
    //here I want to avoid the work from MyVariable<T>::nonconst()
    return this->_element.at(std::forward<Arg>(arg));
}
模板
在(Arg&&Arg)->decltype(((T*)nullptr)->在(Arg))自动非约束
{
//在这里,我想避免MyVariable::Noncost()的工作
在(std::forward(arg))处返回此->_元素;
}

它很难看,但似乎确实有效。

它看起来像一个编译器错误。在您的代码中编译。在
gcc5.2.0
上运行正常,但在
visualstudio 2015
上出现错误,因此确实是编译器问题!克莱恩:编译fine@nullpointer:IDE不相关。您必须编写
此->\u元素
,因为
\u元素
是从属基类的成员。
template<typename Arg>
auto& nonconst_at(Arg&& arg)
{
    //here I want to avoid the work from MyVariable<T>::nonconst()
    return this->_element.at(std::forward<Arg>(arg));
}
template<typename Arg>
auto nonconst_at(Arg&& arg) -> decltype(((T*)nullptr)->at(arg))
{
    //here I want to avoid the work from MyVariable<T>::nonconst()
    return this->_element.at(std::forward<Arg>(arg));
}