c++ - 具有已知返回值的特定签名的生成函数
问题描述
有没有办法生成一个静态函数(指针):1.具有特定的签名。2. 返回特定值。3. 忽略所有论点。
就像是:
template<typename ReturnType, ReturnType defaultValue, typename... Args>
ReturnType FallbackFunction(Args... ) {
return defaultValue;
}
int threeParamFunction(int one, int two, int three)
{
return one + two + three;
}
float twoParamFunction(float one, float two)
{
return one + two;
}
int main()
{
// This somehow works
using ThreeParamFunction = decltype(&threeParamFunction);
ThreeParamFunction fncPointerZero = FallbackFunction<int, 0>;
cout << "Returning zero: " << fncPointerZero(5, 10, 15) << std::endl;
ThreeParamFunction fncPointerOne = FallbackFunction<int, 1>;
cout << "Returning one: " << fncPointerOne(5, 10, 15) << std::endl;
// Does not compile:
//using TwoParamFunction = decltype(&twoParamFunction);
//TwoParamFunction fncPointerSeven = FallbackFunction<float, 7.0f>;
//cout << "Returning seven: " << fncPointerSeven(5, 10) << std::endl;
return 0;
}
如果应用程序无法加载正确的函数,动机是生成一个返回已知值的回退函数。
解决方案
您不能采用模板函数的地址/类型(但您可以针对特定实例)。
所以你的
auto f0 = &FallbackFunction<int, 0>; // decltype(f0) is `int (*)()` not `int (*)(Ts...)`
但事实上,在你的情况下
int (*fncPointer)(int, int, int) = &FallbackFunction<int, 0>;
// Only FallbackFunction<int, 0, int, int, int> is valid
// it is mostly static_cast<int (*)(int, int, int)>(&FallbackFunction<int, 0>)
// Which force deduction to FallbackFunction<int, 0, int, int, int>.
所以要么指定所有参数:
auto f2 = &FallbackFunction<int, 0, int, int>; // decltype(f2) is `int (*)(int, int)`
operator()
或者您可以使用(使用 lambda)创建函子:
auto foo = [](auto...){ return 0; };
foo(); foo(1); foo(1, 2, 3);
auto bar = [](auto...){ return 4.2f; };
bar(); bar(1); bar(1, 2, 3);
此外,float
不是有效的非类型参数:
template <float f> struct S{}; // invalid.
推荐阅读
- php - 为什么通过联系表格发送的消息都进入垃圾邮件箱?我的代码有什么问题?
- javascript - Wixcode/Database - 在显示来自数据库的数据之前对用户进行身份验证
- android - Android SoundPool 指南
- angular - 如何使用 Angular 5 进行遮罩
- java - 注入构造函数时出错,java.nio.file.AccessDeniedException
- spring - spring 5.0.6 无法通过 addResourceHandler 和 thymeleaf 导入静态资源
- android - 在 Android Studio 中使用 AsyncTask 解析在线 XML 文件时出现 NetworkOnMainThreadException
- html - HTML 垂直导航栏高度到页脚
- angular6 - 如何将应用程序服务导入库
- css - 在 em 中遵循 .0 是必需的还是偏好?