我正在尝试为“概念”输入参数分配默认值:
#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/