无法将std::optional::value传入std::views::transform的问题排查
为什么
std::optional::value无法传递给std::views::transform,但has_value可以? 尝试将std::optional::value的成员函数指针传给std::views::transform时编译报错,但传递std::optional::has_value却能正常运行,测试代码如下:
#include <optional> #include <ranges> #include <vector> int main () { std::vector<std::optional<int>> myVec{{1,2,3}}; const auto result = myVec | std::views::filter(&std::optional<int>::has_value) | std::views::transform(&std::optional<int>::value); return 0; }
使用x86-64 clang 16.0.0并添加
-std=c++20编译选项时,得到如下错误:
<source>:15:11: error: no matching function for call to object of type 'const _Transform' | std::views::transform(&std::optional<int>::value); ^~~~~~~~~~~~~~~~~~~~~ /opt/compiler-explorer/gcc-12.2.0/lib/gcc/x86_64-linux-gnu/12.2.0/../../../../include/c++/12.2.0/ranges:891:2: note: candidate template ignored: substitution failure: deduced incomplete pack <(no value)> for template parameter '_Args' operator()(_Args&&... __args) const ^ /opt/compiler-explorer/gcc-12.2.0/lib/gcc/x86_64-linux-gnu/12.2.0/../../../../include/c++/12.2.0/ranges:2057:2: note: candidate function template not viable: requires 2 arguments, but 1 was provided operator() [[nodiscard]] (_Range&& __r, _Fp&& __f) const ^ 1 error generated. Compiler returned: 1
原因分析
问题出在函数重载的歧义上:
std::optional::value存在两个重载:普通版本T& value()和const版本const T& value() const。当你传递&std::optional<int>::value时,编译器无法确定要选用哪个重载,而std::views::transform的模板推导机制无法自动解决这种歧义。- 而
std::optional::has_value只有一个const成员函数版本:bool has_value() const noexcept;,不存在重载冲突,因此编译器可以直接解析出正确的函数指针,顺利通过编译。
解决办法
方法1:使用lambda表达式(临时解决方案)
通过lambda明确调用value(),避免重载歧义:
const auto thisWorks = myVec | std::views::filter(&std::optional<int>::has_value) | std::views::transform([] (const auto& opt) {return opt.value();});
方法2:显式指定函数指针类型
通过static_cast明确指定要使用的value重载版本:
const auto result = myVec | std::views::filter(&std::optional<int>::has_value) | std::views::transform(static_cast<const int& (std::optional<int>::*)() const>(&std::optional<int>::value));
内容的提问来源于stack exchange,提问作者antonio
相关产品推荐
相关产品推荐

