Practice mode C++

Assuming standard headers and using namespace std, what does this C++ code print? template <typename T> struct Id { static const int v = 1; }; template <> struct Id<int> { static const int v = 2; }; int main() { cout << Id<char>::v << Id<int>::v; }

Correct answer D. 12

Explanation

Id uses the primary template, so its v is 1. The line template struct Id declares a full (explicit) specialisation, which completely replaces the primary template when T is int, so Id::v is 2. Specialisation lets a template provide custom behaviour for particular types while keeping a generic default.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.