改变函数返回类型 C++

Lee*_* Yi 2 c++ c++14

那么,随着 C++14 中新的auto返回类型推导,有没有办法创建具有不同返回类型的函数呢?

例如:

auto replaceStr(string base, string search, string replace) {
  size_t found = base.find(search);
  if (found == string::npos) {
    return false; //Return this is replace is not found
  }
  else {
    base.replace(found, (found+search.length()), replace);
    return base; //Return this after the replacement
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道这行不通。那么有没有办法让它发挥作用呢?

编辑:评论中的大多数人都告诉我这是不可能的,因为编译器不知道函数在编译时的返回类型。那么也许我们可以让函数具有默认返回类型和可选返回类型?

Var*_*lex 5

C++ 是一种静态类型语言:无法返回编译时未知的变量类型。

请参阅有关静态和动态类型语言差异的SO问题,也称为弱类型或强类型

关于 C++14auto返回类型,请参阅何时应该使用 C++14 自动返回类型推导?