强制函数只能用特定类型调用

Force function to be called only with specific types

本文关键字:类型 调用 函数      更新时间:2023-10-16

我正在考虑在c++ 11中将char*转换为bool时强制类型安全,建议如果您这样做

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(现场示例)编译代码,我得到了以下错误:

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是正确的,我的程序是病态的,这只是意味着它不会编译或它是未指定或未定义的行为?

您的程序格式错误。首先,对于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和,from [dcl.fct.def.delete]:

一个程序隐式或显式地引用一个被删除的函数,而不是声明它,是病态的。

这不是未定义或未指定的行为。它不应该被编译。