LearnFrenzy
Sign in Take a free test

Abstraction · Find the Error · Question 10

Error: calling a constrained template with the wrong type Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <concepts>
#include <iostream>
#include <string>

template <typename T>
    requires std::integral<T>
T half(T x) { return x / 2; }

int main() {
    std::cout << half(10) << '\n';
    std::cout << half(std::string("ten")) << '\n';
    return 0;
}
  • A requires must come before template
  • B std::string is not an integral type, so the requires clause rejects half(std::string) Correct
  • C half(10) is ambiguous
  • D std::integral needs <type_traits>
Correct Answer: Option B

The constraint documents and enforces the abstraction "half of an integer".

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