9

I'm pretty new to programming and can't really understand why I can't just declare argument types the same way I do with normal variables and have to declare the type again and again.

I mean, why must I:

Func(int a, int b, float c)

instead of

Func(int a, b, float c)

?

As long as they're the same type, of course.

  • Can I actually do that and just don't know how to?

If it is possible, please tell me how.

Thanks in advance.

@0x499602D2: If parameter declarations were more closely analagous to object declarations, then void f(int a, float c, d) would presumably be equivalent to void f(int a, float c, float d). The language could have made this work correctly and consistently. It just didn't. – Keith Thompson

This answered my question best. but it's a comment...

4

5 回答 5

6

这就是为什么:

一切都有一些规则或合同。理论上,您可以编写一个 C 编译器,而不是:

func(int a, int b)

拿着这个:

func(int a, b)

那很好。

C 的创建者决定每个形式参数都必须附加其类型,因此我们今天拥有它。这只是您必须遵守的约定。

而且您必须遵循它,因为 C/C++ 解析器希望您这样做,否则它将无法理解您。

同样你的问题:

有没有办法用一种类型声明多个函数参数?

理论上可以这样写:

有多种方法是用一种类型声明函数参数吗?

如果您同意某人以这种方式提出问题,则您必须遵守本合同 - 期限。

于 2013-11-06T22:54:46.937 回答
2

语法就是这样。我不知道有什么“原因”,但在(旧)C 参数中没有显式类型将默认为 int (甚至在右括号之后提供类型的语法),所以我不确定这可以安全地放宽。

于 2013-11-06T22:35:15.037 回答
1

不,我不这么认为。

然而,在你的函数声明中,你可以省略变量名。

Func(int a, int b);

Func(int, int);

编译器只需要关于签名的足够信息,以便能够确定在运行时调用哪个函数。

于 2013-11-06T22:33:30.517 回答
1

如果您希望 b 具有与 a 相同的类型(以防您稍后更改 ab 的类型应该反映这一点),c++11您可以这样做:

void Func( int a, decltype(a) b );

如果你想完全省略 type,你不能这样做。简单的答案是:语法不支持。为什么?可能有很多答案,其中之一:

void func( int, int ); // function declaration

我们现在放什么?

void func( int, ); // function declaration? ugly and unreadable

它也容易出错:

void func( int a, foobar ); // suppose this works
                            // now we add #include where foobar is defined as a struct
                            // function suddenly changes it's signature

我很确定会有更糟糕的副作用,所以请相信,你不希望这样。

于 2013-11-06T22:51:45.000 回答
0

我意识到这并不能完全回答可能提出的问题,但它确实回答了所提出的问题:是的,可以声明一个函数,say f,它接受N类型的参数T(并返回RC)而不重复,T尽管使用了一个有趣的符号:

same_type_function<void, 2, int> f;

可以为成员函数做类似的事情。但是请注意,我认为也不可能定义这样的函数!此外,您显然需要定义same_type_function. 以下是如何实现此模板的快速示例:

#include <iostream>

template <typename RC, int N, typename T, typename... A>
struct same_type_function_aux;

template <typename RC, typename T, typename... A>
struct same_type_function_aux<RC, 0, T, A...> {
    typedef RC (type)(A...);
};

template <typename RC, int N, typename T, typename... A>
struct same_type_function_aux {
    typedef typename same_type_function_aux<RC, N-1, T, T, A...>::type type;
};

template <typename RC, int N, typename T>
using same_type_function = typename same_type_function_aux<RC, N, T>::type;

same_type_function<void, 2, int> f;

int main()
{
    f(1, 2);
}

void f(int a, int b) {
    std::cout << "called f(" << a << ", " << b << ")\n";
}
于 2013-11-06T22:47:44.677 回答