具有已知返回值的特定签名的生成功能

时间:2019-04-12 22:50:48

标签: c++ variadic-templates

是否有一种生成静态函数(指针)的方法:  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;
}

动机是生成一个回退函数,如果应用程序无法加载适当的函数,则该函数将返回已知值。

1 个答案:

答案 0 :(得分:2)

您不能获取模板功能的地址/类型(但可以用于特定实例)。

所以你

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.