自动推导别名模板和模板类的模板参数
Automatic deduction of template parameters for alias templates and template classes
我想使无状态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 + ...);
};
- 部分定义/别名模板模板参数
- 告诉c++编译器该参数没有别名
- 为什么我们不能重复使用具有不同模板参数的别名模板标识符?
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- 模板模板参数和模板别名:编译器错误?
- 为模板参数包添加别名
- C++使用默认模板参数键入别名和转发声明
- 缺少别名模板C++参数列表
- 使用外部定义的模板类型作为模板参数的更通用模板的模板别名
- 必须非常量别名参数及其默认参数常量
- 作为模板参数 c++ 给出的类的别名模板
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 参数化类的别名(或类型定义)内部类
- C++别名的模板参数包扩展
- 如何简化模板模板参数中的enable_if别名
- 包含可变参数包的第一个可转换类型的别名的结构
- C++ 11 个模板,参数包的别名
- 为什么模板引用类型不能用作模板类型别名参数?
- 具有模板类默认参数的 C++17 别名模板
- 如何用可变数量的参数别名一个函数