强制函数只能用特定类型调用
Force function to be called only with specific types
我正在考虑在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]:
一个程序隐式或显式地引用一个被删除的函数,而不是声明它,是病态的。
这不是未定义或未指定的行为。它不应该被编译。
相关文章:
- 通过模板函数对未知类型调用方法
- C++ 在不知道子类型的情况下从父类型调用子方法
- 如何在 cpp 模板中根据实际类型调用整型?
- <未解析的重载函数类型>调用二进制谓词
- 如何使用模板根据数据类型调用函数?
- 统一处理具有协变类型的函数指针(如何使用派生类型调用回调?
- 使用模板化类型调用的模板化函子
- NDK带有JNI的ndk,使用返回类型的非原始类型调用方法
- 如何使用不同的数据类型调用相同功能
- 是否可以根据基于的范围类型调用不同的取消引用运算符重载
- 如何在C++中根据模板类型调用函数
- 重载下标运算符以根据分配的类型调用函数
- C++传递函数以按参数按模板类型调用
- C++类继承从基类型调用子方法
- 根据类型调用不同的函数
- 从数据类型调用构造函数(或任何函数/方法)而不经历两个模板化函数的任何类型的方法
- 循环unique_ptrs的向量,并为运行时类型调用正确的重载
- 根据类型调用不同的函数
- 数据类型调用模板方法
- 未为派生类型调用函数模板专用化