有关为模板提供默认类型的问题
Question about providing default type for a template
例如,我写了以下一段代码:
struct default_type {};
template <typename U = default_type> auto func(int x, U u) {
if constexpr(is_same<U, default_type>::value) {
return x * 2;
}
else {
return u(x);
}
}
int main() {
cout << "5 + 3 = " << func(5, [](int x){ return x + 3; }) << endl;
cout << "5 * 2 = " << func(5) << endl;
}
但这给出了编译器错误"没有匹配函数来调用'func(int)'"。正确的方法是什么?
您提供了默认类型,但没有默认值。该函数仍然需要两个参数,并且default_type
将被推导的参数覆盖,使其无用。
这样做:
template <typename U = default_type>
auto func(int x, U u = {}) { ... } // (1)
我不能用确切的标准来支持这一点,但简而言之:U
是在模板参数推导阶段获得的(没有推导规则 - 不考虑默认函数参数,因此默认),这在重载解决阶段之前,此时默认函数参数被解释,已经知道U
的类型,这使得列表初始化有效。
是的,你也可以写:
template <typename U = default_type>
auto func(int x, U u = U()) { ... } // (2)
或
template <typename U = default_type>
auto func(int x, U u = default_type()) { ... } // (3)
显式提供U
类型时语义略有不同(我认为您不会):
func<not_the_default_type>(5);
在这里,(1) 和 (2) 是等价的,但在 (3) 中,U
的构造是通过构造一个临时default_type
来实现的,然后将其转换为not_the_default_type
。
最后,完全相反的错误是期望在这里推导出U
:
template <typename U>
auto func(int x, U u = default_type()) { ... }
事实并非如此。请参阅此问答。
相关文章:
- 具有默认模板类型的默认构造函数的类型推导
- C++(和 ROS) - 包含与前向声明引用,设置默认值和类型定义
- 模板类默认类型和条件
- 具有默认类型和值的模板参数
- 在一行中将默认类型值上的指针作为参数传递
- 模板中默认类型的重载运算符
- 当“std::make_index_sequence”和“std::index_sequence”用于模板参数默认类型时
- 所有版本的 GCC 都在与定义中具有默认类型的模板作斗争
- 有关为模板提供默认类型的问题
- eigen:模板函数中矩阵的默认类型
- 可以将枚举的默认类型设置为无符号字符
- 是否可以为缺少的模板成员类型创建默认类型?
- 如何在C++中为类返回默认类型
- 函数模板:默认类型参数
- 模板默认类型vs默认值
- 使用默认类型替换c++函数引用模板错误
- 模板函数的默认类型假设
- 在C++中,用十六进制或八进制表示的整型文字的默认类型是什么
- 如何在c++中定义默认类型转换操作符
- 错误:不明确的默认类型转换(c++)