3

Where should i put the override keyword?

Eclipse indexer throws an error in one example and my compiler with the second example.

Base class:

template<typename type, size_t N>
class Base<type[N]>
{
  virtual type const (& Get() const)[N];
};

Derived class:

Example 1) Eclipse error. Compiler OK

template<typename type, size_t N>
class Derived : Base<type[N]>
{
  virtual type const (& Get() const override)[N];
};

Example 2) Eclipse Ok. Compiler error

template<typename type, size_t N>
class Derived : Base<type[N]>
{
  virtual type const (& Get() const)[N] override;
};

Edit: The stack-overflow syntax highlighting also doesn't recognize override as a keyword.

vuko_zrno
  • 635
  • 1
  • 8
  • 18

1 Answers1

2

Suggestion:

Make your life easier with judicious use of using (or typedef):

#include <cstddef>
#include <type_traits>

template<class T> class Base;

template<typename type, size_t N>
class Base<type[N]>
{
public:
    using array_type = std::add_const_t<type>[N];
    using array_reference = array_type&;

  virtual array_reference Get() const;
};


template<class Array>
class Derived : public Base<Array>
{
    using base_class = Base<Array>;
public:
    using array_reference = typename base_class::array_reference;

    virtual array_reference Get() const override;
};

int main()
{
    auto x = Derived<int[10]>();

    auto br = static_cast<Base<int[10]>&>(x);

    auto&& y = br.Get();
}

But to answer your specific question:

#include <cstddef>

template<class T> class Base;

template<typename type, size_t N>
class Base<type[N]>
{
public:
    virtual type const (& Get() const) [N];
};

template<class T> class Derived;

template<typename type, size_t N>
class Derived<type[N]> : public Base<type[N]>
{
public:
    virtual type const (& Get() const override)  [N] ;
};

int main()
{
    auto x = Derived<int[10]>();

    auto br = static_cast<Base<int[10]>&>(x);

    auto&& y = br.Get();
}

https://godbolt.org/g/q16ns7

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • 1
    I agree that typedef or using is needed to clear the syntax here but why `std::add_const_t[N]` instead of `const type[N]` ? – Tyker Aug 10 '18 at 14:36
  • @Tyker good point. I was concerned that if `type` was `const int` then this would expand to `const const int`, but I am wrong. The compiler seems to be happy with it. however, in general I use std::add_const_t, std::add_lvalue_reference_t etc (if I remember) as I feel it increases clarity. – Richard Hodges Aug 10 '18 at 15:37