C++按返回类型选择函数

ano*_*non 4 c++ polymorphism function

我意识到标准C++只能通过参数类型选择函数,而不是返回类型.即我可以做类似的事情:

void func(int);
void func(double);
Run Code Online (Sandbox Code Playgroud)

但不是

double func();
int func();
Run Code Online (Sandbox Code Playgroud)

在前者中,很明显,在后者中,它是暧昧的.是否有任何扩展允许我告诉C++选择哪个函数也可以使用返回类型?

谢谢!

jpa*_*cek 11

您不能在同一范围内具有两个具有相同名称和签名的函数(即参数类型).然而,您可以根据分配结果的变量创建一个行为不同的函数,如:

int x=f();
double x=f(); // different behaviour from above
Run Code Online (Sandbox Code Playgroud)

通过f()使用重载的强制转换运算符返回代理.

struct Proxy
{
  operator double() const { return 1.1; }
  operator int() const { return 2; }
};

Proxy f()
{
  return Proxy();
}
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/ehUM1

并不是说这个特定的用例(返回不同的数字)是有用的,但这个成语有用.


Jam*_*lis 9

如果您有这两个函数,那么如果您只是调用,编译器应该选择哪个函数:

func();
Run Code Online (Sandbox Code Playgroud)

最接近你要求的是使用专门的函数模板(请注意,在专门化函数模板时要非常小心):

template <typename ReturnT>
ReturnT func();

template <>
double func<>() { return 42; }

template <>
int func<>() { return 0; }
Run Code Online (Sandbox Code Playgroud)

然后你可以按如下方式调用它:

func<int>();
func<double>();
Run Code Online (Sandbox Code Playgroud)


Jon*_*age 5

为什么不用不同的名字呢?如果他们回归不同的东西,对我来说听起来好像他们可能正在做不同的事情.为什么要混淆你的代码?