New*_*ine 8 c++ templates overloading c++-concepts c++20
(我正在学习概念和模板,所以如果我有什么不对的地方,请纠正我。)我有一个将概念作为参数的函数。我现在试图重载这个需要更具体概念的函数。那会做“更具体的事情”或调用不太具体的功能。
template<typename T>
concept Concept1 = ...;
template<typename T>
concept MoreSpecificConcept = ...;
Concept1 <T> &&
...;
//...
void someFunc(const Concept1 auto& x)
{
//do general stuff
}
void someFunc(const MoreSpecificConcept auto& x)
{
if(...)
{
//do specific stuff
}
else
{
//do the more general thing:
// Problem. Trying to call itself:
someFunc(x);
}
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以明确告诉编译器要调用哪个重载(例如someFunc<Concept1>(x)哪个不起作用),还是仅依赖于传递对象的类型?可以说我不能x转换为更通用的类型,并且更通用的函数/概念不知道这个更具体的函数/概念,所以他们不能用约束排除它。编辑:这些函数应该在同一个(全局)命名空间内。
通常的解决方法是使用单独的辅助函数:
void somefunc(const Concept1 auto& x) {
// general stuff
}
void somefuncSpecific(const Concept1 auto& x) {
somefunc(x);
}
void someFuncSpecific(const MoreSpecificConcept auto& x)
{
if(...)
{
//do specific stuff
}
else
{
//do the more general thing:
somefunc(x);
}
}
Run Code Online (Sandbox Code Playgroud)
没有分离功能的另一种解决方法是使用if constexpr:
void someFuncSpecific(const Concept1 auto& x)
{
if constexpr(MoreSpecificConcept<decltype(x)>)
{
if (...)
{
//do specific stuff
// skip the rest:
return;
}
}
//do the more general thing:
somefunc(x);
}
Run Code Online (Sandbox Code Playgroud)