开发者

C++ using statement in member function scope

开发者 https://www.devze.com 2023-02-12 21:24 出处:网络
If I want to use a member of a template base class from a template derived class, I have to bring it into scope as such:

If I want to use a member of a template base class from a template derived class, I have to bring it into scope as such:

template <typename T>
struct base
{
    void foo开发者_Go百科();
};

template <typename T>
struct derived : base<T>
{
    using base<T>::foo;
};

Why can't I place this using statement into a local scope, like other using statements?

template <typename T>
struct base
{
    void foo();
};

template <typename T>
struct derived : base<T>
{
    void f()
    {
        using base<T>::foo;  // ERROR: base<T> is not a namespace
    }
};


The purpose of using base<T>::foo in the function scope is that you want to call foo in the function, and since it gives error, you cannot do that.

If you want to call the functon (otherwise why you would do that), then you can do these which are allowed:

this->template base<T>::foo(); //syntax 1
this->base<T>::foo();          //syntax 2 - simple
this->foo();                   //syntax 3 - simpler

However, you cannot write this:

foo() ;  //error - since foo is in base class template!
//if you write `using base<T>::foo` at class scope, it will work!

Demo at ideone : http://www.ideone.com/vfDNs

Read this to know when you must use template keyword in a function call:

Ugly compiler errors with template


The standard (draft 3225) says in [namespace.udecl]:

A using-declaration for a class member shall be a member-declaration. [ Example:

struct  X  {
    int  i;
    static  int  s;
};
void  f()  {
    using  X::i; // error:  X::i is a class member
                 // and this is not a member declaration.
    using  X::s; // error:  X::s is a class member
                 // and this is not a member declaration.
}

— end example ]

A using-directive has no such restriction, however ([namespace.udir]):

when looking up a namespace-name in a using-directive, only namespace names are considered

0

精彩评论

暂无评论...
验证码 换一张
取 消