英文:
How to assign a default argument to a concept input parameter
问题
我试图为一个名为"concept"的输入参数分配一个默认值:
#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(); // 编译错误
return 0;
}
但是当省略参数时,我会得到编译错误:
main.cpp: 在函数‘int main()’中:
main.cpp:14:8: 错误:没有匹配的函数调用‘foo()’
14 | foo(); // 无法编译通过
| ~~~^~
main.cpp:4:6: 注释:候选项:‘template<auto:11> requires integral void foo(auto:11)’
4 | void foo(std::integral auto num = 1)
| ^~~
main.cpp:4:6: 注释:模板参数推导/替代失败:
main.cpp:14:8: 注释:无法推导模板参数‘auto:11’
14 | foo(); // 无法编译通过
| ~~~^~
如果无法为概念分配默认参数,那么当我调用'foo'时,带参数能编译通过,但不带参数时不能。
我做错了什么?
我可以用foo<int>()
替换foo()
,它会工作,但我不应该这样做。
我也可以用以下方式替换'foo'的定义:
template<typename T = int> requires std::integral<T>
void foo(T num = 1)
这样也能正常工作,但我不应该这么明确。
英文:
I'm trying to assign a default value to a "concept" input parameter:
#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;
}
But I get a compilation error when the argument is omitted:
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
| ~~~^~
If assigning a default argument to a concept is not possible,
then I find it strange that the program compiles when I call 'foo' with arguments, but not without.
What am I doing wrong?
I can replace foo()
with foo<int>()
and it'll work, but I shouldn't have to do that.
I can also replace the definition of 'foo' with:
template<typename T = int> requires std::integral<T>
void foo(T num = 1)
And it'll once again work, but I shouldn't have to be that explicit.
答案1
得分: 3
函数中的模板参数类型无法从默认参数中推断出,并且对于该概念没有规则更改。在这种情况下,您仍然需要为模板参数提供默认类型。
template<std::integral T = int>
void foo(T num = 1)
{
std::cout << "Num: " << num << std::endl;
}
英文:
The types of template parameters in functions cannot be deduced from default arguments, and there is no rule change for the concept. In this case, you still need to provide the default type for the template parameter
template<std::integral T = int>
void foo(T num = 1)
{
std::cout << "Num: " << num << std::endl;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论