c++ - 用概念重载函数

标签 c++ templates overloading c++20 c++-concepts

(我正在学习概念和模板,所以如果我有什么不对的地方,请纠正我。)我有一个将概念作为参数的函数。我现在试图重载这个需要更具体概念的函数。那会做“更具体的事情”或调用不太具体的功能。

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);
  }
}
有什么方法可以明确告诉编译器要调用哪个重载(例如 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);
  }
}
另一种没有分离功能的解决方法是使用 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);
}

关于c++ - 用概念重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67725541/

相关文章:

c++ - 返回引用是什么意思?

c++ - 在 50...60 个文件之间传递类对象

c++ - 二维数组的自动大小扣除

c++ - 如何选择函数指针类型?

c++ - 当与错误检查宏一起使用时,具有两个类型参数的模板函数无法编译

c++ - 重载二元运算的正确方法

c++ - 如何在一行中检查 std::vector 中是否存在元素?

c++ - 如何在 Windows 中使用手写的 makefile 编译和构建 C++ 应用程序?

inheritance - 为什么重载的成员函数只有在 D 中没有被覆盖的情况下才会自动继承?

c# - 动态和其他类型的重载方法