Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using statement in member function scope

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

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
    }
};
like image 413
HighCommander4 Avatar asked Feb 24 '11 04:02

HighCommander4


1 Answers

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

like image 99
Nawaz Avatar answered Sep 28 '22 06:09

Nawaz