LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Predict the Output · Question 20

One accessor for const and non-const with deducing this Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 20 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

class Playlist {
    std::vector<std::string> songs_{"Intro", "Theme"};
public:
    // C++23: one function replaces the const and non-const overloads
    template <typename Self>
    auto& at(this Self& self, std::size_t i) { return self.songs_[i]; }
};

int main() {
    Playlist p;
    p.at(0) = "Opening";                                       // non-const: returns std::string&
    const Playlist& cp = p;
    std::cout << cp.at(0) << ' ' << cp.at(1) << ' '
              << std::is_const_v<std::remove_reference_t<decltype(cp.at(0))>> << '\n';   // const: const std::string&
    return 0;
}
  • A Opening Theme 1 Correct
  • B Intro Theme 0
  • C Opening Theme 0
  • D Compilation error
Correct Answer: Option A

Self is deduced as Playlist or const Playlist, so the returned reference is writable or const accordingly – no duplicated overloads.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links