Namaran

Code daily. Without assist.

2026-10-24

expect_eq.cpp

#include <iostream>
#include <string>

template <class A, class B> bool expect_eq(const A& actual, const B& expected) {
    return actual == expected;
}

const char* greet() {
    static std::string s = "hi";
    return s.c_str();
}

int main() {
    std::cout << expect_eq(std::string("hi"), "hi") << expect_eq(greet(), "hi") << '\n';
}

これは何を出力するでしょうか?

Answer

10 です。

expect_eq の == が何を比べるかは、テンプレート引数の型で決まります。1つ目の呼び出しでは A が std::string なので、std::string と文字列リテラルを比べる operator== が選ばれ、中身の "hi" どうしが比べられて 1 になります。

2つ目の呼び出しでは A が const char*、B が char[3] です。ポインタと配列を == で比べると、配列の expected は先頭要素へのポインタに変換され、組み込みのポインタの比較になります。この比較が見るのは指している番地で、文字ではありません。greet() が返すのは static な std::string が持つ領域の番地で、リテラル "hi" の番地とは別の場所なので、文字が同じでも結果は 0 です。

1つ目と同じく中身を比べると読むと 11 と答えることになり、このテストは正しい greet を失敗と報告します。C の文字列の中身を比べるなら、std::string_view に変換してから比べるか、std::strcmp を使います。