banner
cells

cells

为美好的世界献上 code

Q338

Q338#

// using C++17
#include <iostream>
#include <string>
#include <type_traits>

template<typename T>
int f() {
    if constexpr (std::is_smae_v<T, int>) {
        return 0;
    } else {
        return std::string {};
    }
}

int main() {
    std::cout << f<int>();
}

Explain#

The function template f is only over instantiated for int. In this case, the if constexpr is ture, and the function returns 0. The { return std::string{} } statement is a discarded statement. in fact it is undefined behaviour!

GCC and Clang gives a compilation error complaining they can't convert std::string to int, whereas MSVC prints 0.

Answer#

click to see answer The program is undefined
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.