有没有办法生成一个静态函数(指针):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.