3

I know using in C++11 behaves same as typedef. I have this code and found different use cases:

template<typename T, int a>
class Base
{
public:
     std::vector<T> noise_(a);
     using VectorType = std::vector<T>;
     virtual VectorType getVector() const
     {
        return noise_;
     }
protected:
     VectorType noise_;
};

template<typename T, int a> 
class Derived : public Base<T,a>
{
public:
    using Base<T,a>::noise_;
    using VectorType = typename Base<T,a>::VectorType; 
    using Base<T,a>::getVector;
};

Here, using is used in 3 different way. What is the purpose of the following line (noise_ is a protected member of the base class):

using Base<T,a>::noise_;

Same for:

using Base<T,a>::getVector;
TonyParker
  • 2,024
  • 5
  • 18
  • 27
  • 3
    cppreference is a really good reference to use if you want know know about a language feature: https://en.cppreference.com/w/cpp/language/using_declaration – NathanOliver Jan 25 '19 at 15:58
  • 2
    There is one significant difference between `using` and `typedef`: Only the former can be used for [alias templates](https://en.cppreference.com/w/cpp/language/type_alias). – Max Langhof Jan 25 '19 at 16:37

1 Answers1

7

Simply put, when the base class depends on a template parameter, its scope is not inspected to resolve names. Hence, you cannot refer to noise_ in Derived using just noise_. You should either write this->noise_, or introduce the name with using.

Evg
  • 25,259
  • 5
  • 41
  • 83
  • can you please this line, "when the base class depends on a template parameter, its scope is not inspected to resolve names". – TonyParker Jan 29 '19 at 16:28
  • @TonyParker, could I please what? – Evg Jan 29 '19 at 17:16
  • explain this line – TonyParker Jan 30 '19 at 09:02
  • 1
    @TonyParker, `Derived` has a template parameter `T` (let's omit `a` for brevity) and is derived from `Base` that depends on that same `T`. Public and protected members of `Base` are visible inside `Derived`, but you can't access them using just their names, because the compiler will not look into `Base` scope without your special instruction. You should either write `this->name` or `using Base::name`. If `Base` does not depend on `T` (say, you derive from `Base`), this rule does not apply and `Base` members will be accessible inside `Derived` without `this->` or `using`. – Evg Jan 30 '19 at 09:39