c++ - 如何为概念输入参数分配默认参数

标签 c++ c++20 auto c++-concepts default-arguments

我正在尝试为“概念”输入参数分配默认值:

#include <concepts>
#include <iostream>

void foo(std::integral auto num = 1)
{
    std::cout << "Num: " << num << std::endl;
}

int main()
{
    foo(7);
    foo(true);
    foo('&');
    //foo();  // Does not compile
    return 0;
}

但是当省略参数时,我收到编译错误:

main.cpp: In function ‘int main()’:
main.cpp:14:8: error: no matching function for call to ‘foo()’
   14 |     foo();  // Does not compile
      |     ~~~^~
main.cpp:4:6: note: candidate: ‘template  requires  integral void foo(auto:11)’
    4 | void foo(std::integral auto num = 1)
      |      ^~~
main.cpp:4:6: note:   template argument deduction/substitution failed:
main.cpp:14:8: note:   couldn’t deduce template parameter ‘auto:11’
   14 |     foo();  // Does not compile
      |     ~~~^~

如果无法为概念分配默认参数, 然后我发现奇怪的是,当我使用参数调用“foo”时,程序会编译,但没有参数时则不会。

我做错了什么?

我可以替换foo()foo<int>()它会起作用,但我不应该这样做。

我还可以将“foo”的定义替换为:

template<typename T = int> requires std::integral<T>
void foo(T num = 1)

它会再次起作用,但我不必那么明确。

最佳答案

函数中模板参数的类型cannot be deduced来自默认参数,并且该概念没有规则更改。在这种情况下,您仍然需要为模板参数提供默认类型

template<std::integral T = int>
void foo(T num = 1)
{
  std::cout << "Num: " << num << std::endl;
}

关于c++ - 如何为概念输入参数分配默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76657399/

相关文章:

c++ - C++20 宇宙飞船运算符的性能问题?

C++14 auto lambda 可以接受 Obj<std::tuple<void>>——但模板函数不能?

c++ - 为什么 auto 类型不能与 for 语句 C++ 中的其他内置类型共存

c++ - 为什么 void 在 C++ 中不采用 void 值?

c++ - 结构体非类型模板参数+聚合初始化: standard in c++20 or not

c++ - 我怎样才能为一个概念重载一个函数?

c++ - lambda 中的递归调用 (C++11)

c++ - 警告从 lambda 返回捕获的引用

c++ - cMake 找不到 BOOST_TIMER_LIBRARIES

c++ - 确定 Visual Studio 2015 调试器中每个帧的堆栈大小