我正在查看enforcing type safety when casting char* to bool in C++11,如果你这样做,建议
template<typename T>
void foo(T) = delete;
void foo(int f) {}
foo
只有在给出明确的int
参数时才会起作用。我做了一个测试用例:
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));
}
我使用coliru用g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
(live example)编译代码,我收到以下错误:
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;
^
用clang编译的也产生了类似的错误
现在当我在cppreference上阅读= delete
时,它说明了
如果函数超载,则首先进行重载解析,如果选择了删除的函数,则程序只会格式错误。
因此,如果cppreference是正确的并且我的程序格式错误,这只是意味着它不会编译,还是未指定或未定义的行为?
答案 0 :(得分:9)
您的计划格式不正确。首先,对于foo
的每次调用,我们执行重载决策。那会叫:
foo(1); // foo(int )
foo(3.0); // foo<T>, T=double
foo(short(5)); // foo<T>, T=short
foo(float(7.0)); // foo<T>, T=float
foo(long(9)); // foo<T>, T=long
其中四个函数明确deleted
,而且来自[dcl.fct.def.delete]:
除了声明它之外,隐式或显式引用已删除函数的程序是不正确的。
这不是未定义或未指定的行为。它应该根本不编译。