Trailing Return Types and Function Qualifiers

How do I use trailing return types with const, override, or final qualifiers?

When using trailing return types with function qualifiers like const, override, or final, the order of elements is important.

The const qualifier goes before the trailing return type:

class MyClass {
public:
  auto GetValue() const -> int {
    return value;
  }
private:
  int value;
};

But override and final go after the trailing return type:

class Base {
public:
  virtual auto GetValue() const -> int {
    return 10;
  }
};

class Derived : public Base {
public:
  auto GetValue() const -> int override {
    return 20;
  }
};

class MostDerived : public Derived {
public:
  auto GetValue() const -> int final {
    return 30;
  }
};

Remember:

  • const -> return type
  • return type -> override / final

This order can take some getting used to, especially since with traditional function syntax, all these qualifiers would go at the end. But with trailing return types, const moves to the beginning.

Trailing Return Types

An alternative syntax for defining function templates, which allows the return type to be based on their parameter types

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to Use Trailing Return Types in C++
In what situations is it beneficial or necessary to use trailing return types in C++ functions?
Trailing Return Types and auto
How do trailing return types relate to the auto keyword in C++?
Using decltype with Trailing Return Types
How can I use decltype in combination with trailing return types?
Advantages of Trailing Return Types
Apart from template functions, what are some other advantages of using trailing return types in C++?
Best Practices for Trailing Return Types
What are some best practices to follow when using trailing return types in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant