Nat*_*ica 3 c++ language-lawyer c++11
我正在考虑在C++ 11中将char*转换为bool时强制执行类型安全性,如果你这样做,则建议你这样做
template<typename T>
void foo(T) = delete;
void foo(int f) {}
Run Code Online (Sandbox Code Playgroud)
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));
}
Run Code Online (Sandbox Code Playgroud)
我用coliru用g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
(实例)编译代码,我得到了以下错误:
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;
^
Run Code Online (Sandbox Code Playgroud)
用clang编译也产生了类似的错误
现在,当我读到= delete
关于cppreference它说
如果函数过载,则首先发生重载解析,如果选择了删除的函数,则程序只会格式错误.
因此,如果cppreference是正确的并且我的程序是格式错误的,这只是意味着它不会编译,还是未指定或未定义的行为?
你的程序格式不正确.首先,对于每次调用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
Run Code Online (Sandbox Code Playgroud)
其中四个函数是明确的deleted
,来自[dcl.fct.def.delete]:
除了声明它之外,隐式或显式引用已删除函数的程序是不正确的.
这不是未定义或未指定的行为.它应该根本不编译.
归档时间: |
|
查看次数: |
218 次 |
最近记录: |