c++ - 编译器不应该能够从概念中推断出模板参数吗?
问题描述
在下面的代码中,编译器不应该能够从概念中推断出模板参数吗?
#include <iostream>
template<typename T>
struct Bar;
template<typename F, typename T>
concept Foo = requires (F foo, Bar<T> bar)
{
{ foo.test(bar) } -> std::same_as<T>;
};
template<typename T>
struct Bar
{
T value;
template<Foo<T> F>
T test(F foo)
{
return foo.test(*this);
}
};
template<typename T>
struct FooBar
{
T value;
T test(Bar<T> bar)
{
return (value = bar.value) + bar.value;
}
};
int main(void)
{
Bar<float> b{ 1 };
std::cout << b.test(FooBar{}) << std::endl; // Fails to deduce the template argument
std::cout << b.test(FooBar<float>{}) << std::endl; // Compiles successfully
}
这是 MSVC 和 GCC 尚未实现的功能(两者都无法编译代码)吗?还是只是无效的 C++20 代码?如果是这样,为什么?模板参数不是float
唯一可能的类型T
吗?或者是否有一些我遗漏的替代方法可能会导致编译器产生歧义?
解决方案
编译器究竟要从什么推导出模板参数FooBar{}
?您没有提供任何参数,也没有特殊的类模板推导指南,并且模板FooBar
没有默认模板参数。
如果您期望通过使用表达式而不是表达式本身的固有属性(初始化程序中的参数,默认模板参数)来进行模板推导,那么这是错误的期望。
类模板参数推导完全基于提供给类对象的初始化程序的参数,就像函数模板参数推导完全基于提供给函数的参数一样。此后如何使用这两种表达方式都无关紧要。
推荐阅读
- python - 为什么 Python 中会出现错误“模块 'googlesearch' 中没有名称 'search'”?
- kubernetes - Kubernetes pod 获得不同的 CPU 限制
- maven - 如何进行离线 Maven 构建?
- ios - 获取 FinishTransaction() 的 SKPaymentTransaction
- javascript - 显示多个选中复选框的值以及与它们关联的表单为 JSON 格式
- python - 如何在散景图中显示工具栏
- matlab - dx/dt = A*x 使用 Matlab ode23s
- c++ - 使用链接列表搜索哈希表的程序的问题
- python - 为什么while循环没有停止
- nginx - 我如何从外部访问 nginx https,因为它似乎被阻止了?