C++ Quiz52 of 173
Difficulty:
⬅️ Prev: 122Quiz ID: 124Next: 125 ➡️

According to the C++23 standard, what is the output of this program?

#include <iostream>

struct A {};
struct B {};

template<typename T = A>
struct X;

template<>
struct X<A> {
    static void f() { std::cout << 1; }
};

template<>
struct X<B> {
    static void f() { std::cout << 2; }
};

template<template<typename T = B> class C>
void g() {
    C<>::f();
}

int main() {
    g<X>();
}
Hint

What are the scopes of template parameters?

Reveal answer

2

Explanation

§[temp.param]¶16 in the standard says:

A template-parameter of a template template-parameter is permitted to have a default template-argument. When such default arguments are specified, they apply to the template template-parameter in the scope of the template template-parameter.

In this code snippet, the template template-parameter is C, and the scope of C is the function template g(). Therefore, the default template argument for C (which is B) is applied. This means that when g() is called, it is equivalent to calling g>(), which in turn calls X::f(). As X::f() is specialized to print 2, the output of the program is 2.

⬅️ Prev: 122Quiz ID: 124Next: 125 ➡️