自动推导别名模板和模板类的模板参数

Automatic deduction of template parameters for alias templates and template classes

本文关键字:参数 别名      更新时间:2023-10-16

我想使无状态lambda函数与可变模板参数列表递归。但是我需要类型擦除来避免像variable 'lambda' declared with 'auto' type cannot appear in its own initializer这样的错误。可变模板参数表要求对应的函数对象具有模板化的operator ()。对于简单的无状态lambda函数,我可以将其转换为指向简单的自由旧函数的指针,但是如何实现类似的可变无状态lambda函数?我认为我想要的是模板参数列表的自动类型推导(在模板变量的实例化期间:在调用或赋值期间):(伪代码)

#include <type_traits>
#include <iostream>
#include <cstdlib>
template< typename first, typename second, typename ...rest >
using fp = first (*)(first const &, second const &, rest const &...); // at least binary function
int
main()
{
    template fp sum = [] (auto const & first, decltype(first) second, auto const &... rest) { return first + sum(second, rest...); };
    //              ^ assignment                                                                                ^ call
    std::cout << sum(1, 2.0, 3.0f) << std::endl;
    return EXIT_SUCCESS;
}

目前是否有可能实现这样的行为( c++ 14)(例如,使用std::function或其他类型擦除方式)?是否有类似语言特性的提议?或者是已经存在的语言规则完全禁止它?

另一个可能有用的例子:(pseudocode)

template std::vector v{1, 2, 3};
static_assert(std::is_same< decltype(v), std::vector< int > >{});

不,没有办法做你想做的。推导表达式结果的方法是使用auto。没有办法推断函数模板或别名模板的类型。考虑最简单的情况:

std::function<auto> if_this_existed = [](int x, int y) { return x + y; };

你可能期望std::function<int(int, int)>。但是std::function<void(int, int)>是有效的。std::function<long(long, long)>也是如此。真的没有什么可以推断的。此外,对于泛型 lambda,分配特定的类型是没有意义的:

std::function<void(???)> print = [](auto x) { std::cout << x; };

lambda可以用任何可打印的类型调用,但是无论我们在???中放入什么,都会将print限制为该类型。所以这个也失败了。

所以最终,不,你不能递归地写你的泛型可变的lambda。虽然,sum无论如何都不可能递归地编写,因为您无法编写基准情况。编写这种通用sum()的正确方法是使用折叠表达式(c++ 1z):

auto sum = [] (auto const&... args) {
    return (args + ...);
};