Question Preview!
Question #124 Difficulty:
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>();
}
Answer
The program is guaranteed to output: 2
Hint:
What are the scopes of template parameters?
Correct!
§[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<X>()
is called, it is equivalent to calling g<X<B>>()
, which in turn calls X<B>::f()
. As X<B>::f()
is specialized to print 2
, the output of the program is 2
.
You can explore this question further on C++ Insights or Compiler Explorer!