Segfault in C ++ Templates

I have a question about C ++ templates. The following segfaults codes.

template <typename T1, typename T2>
inline T1 const& max(T1 const &a, T2 const &b) {
    return a < b ? b : a;
}
int main() {
    std::cout << max(4.9, 4) << std::endl;
}

However, delete and, and it does the right thing.

template<typename T1, typename T2>
inline T1 const max(T1 const &a, T2 const &b) {
    return a < b ? b : a;
}
int main() {
    std::cout << max(4.9, 4) << std::endl;
}

Also, just use T instead of T1 and T2, and it works just fine.

template<typename T>
inline T const& max(T const &a, T const &b) {
    return a < b ? b : a;
} 

int main() {
    std::cout << max(4, 5) << std::endl;
}

What am I doing wrong here?

+6
source share
2 answers

You should always compile with the warnings turned on, see https://wandbox.org/permlink/KkhFOJw6QNJ7rv7J . If you had warning flags, the compiler would help you and tell you what you are doing wrong.

(. '?:' ( )), int a double. double. , , , , undefined.

+10

.

? , T1, , . . .

, .

. , .

, : .

+1

All Articles