I was looking at enforcing type safety when casting char* to bool in C++11 and it was suggested that if you do
template<typename T>
void foo(T) = delete;
void foo(int f) {}
That foo
will only work when given a explicit int
argument. I made a test case:
template<typename T>
void foo(T) = delete;
void foo(int f) {}
int main()
{
foo(1);
foo(3.0);
foo(short(5));
foo(float(7.0));
foo(long(9));
}
I used coliru to compile the code with g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
(live example) and I got the following errors:
main.cpp: In function 'int main()':
main.cpp:9:12: error: use of deleted function 'void foo(T) [with T = double]'
foo(3.0);
^
main.cpp:2:6: note: declared here
void foo(T) = delete;
^
main.cpp:10:17: error: use of deleted function 'void foo(T) [with T = short int]'
foo(short(5));
^
main.cpp:2:6: note: declared here
void foo(T) = delete;
^
main.cpp:11:19: error: use of deleted function 'void foo(T) [with T = float]'
foo(float(7.0));
^
main.cpp:2:6: note: declared here
void foo(T) = delete;
^
main.cpp:12:16: error: use of deleted function 'void foo(T) [with T = long int]'
foo(long(9));
^
main.cpp:2:6: note: declared here
void foo(T) = delete;
^
compiling with clang also produced similar errors
Now when I was reading about = delete
on cppreference it stated
If the function is overloaded, overload resolution takes place first, and the program is only ill-formed if the deleted function was selected.
So if cppreference is correct and my program is ill-formed does this just mean it will not compile or is it unspecified or undefined behavior?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…