c++ - 为什么 C++ 模板使用尖括号语法?

标签 c++ c++11 language-design template-meta-programming

名义上的问题是指在 1990 年左右引入模板的 C++ 标准中的设计决策。

为什么设计师使用 <> (尖括号)而不是,比如说,() (圆括号)?这样做可以让很多程序员免于与位移相关的错误

std::vector<std::vector<int>> // does not work until C++11

仅在 C++11 中得到修复。我看不出引入类似这样的附加语法的理由,可以说,圆括号可以达到相同的目的,同时保持更改的最小化。 Insted 你可以使用

template(typename T) // Define template if round brackets could be used
mytemplate { ... }
...
...
mytemplate(mytemplate(int)) obj; //Instantiate template when round brackets could be used

精通 C++ 历史的人能否找出使用尖括号的原始设计原理?或者,您能否说明为什么其他解决方案效果不佳?

最佳答案

模板是在 1988 年 USENIX 论文 Parameterized Types for C++ 中引入的由 Bjarne Stroustrup 撰写,后来被纳入 1990 年出版的 The Annotated C++ Reference Manual(标准化 C++ 之前的版本)。根据论文,

The <…> brackets are used in preference to the parentheses (…) partly to emphasize the different nature of template arguments (they will be evaluated at compile time) and partly because parentheses are already hopelessly overused in C++.

9.2. <…> vs (…)

But why use brackets instead of parentheses? As mentioned before, parentheses already have many uses in C++. A syntactic clue (the <…> brackets) can be usedful for reminding the user about the different nature of the type parameters (they are evaluated at compile time). Furthermore, the use of parentheses could lead to pretty obscure code:

template(int sz = 20) class buffer {
    buffer(int i = 10);
    // ...
};
buffer b1(100)(200);
buffer b2(100);      // b2(100)(10) or b2(20)(100)?
buffer b3;           // legal?

These problems would become a serious practical concern if the notation for explicit disambiguation of overloaded function calls were adopted. The chosen alternative seems much cleaner:

template<int sz = 20> class buffer {
    buffer(sz)(int i = 10);
    // ...
};
buffer b1<100>(200);
buffer b2<100>;      // b2<100>(10)
buffer b3;           // b3<20>(10)
buffer b4(100);      // b4<20>(100)

该论文还解释了为什么 templateclass使用关键字。

请注意,Stroustrup 放置了 <…> 变量名之后,与int x[10] 相同。反对(…) ,尽管此位置从未在论文的其他地方使用过。

他关于“使用 (…) 会导致代码模糊/模糊”的论点仍然有效。正如这个问题的评论中提到的,使用括号 T(x)导致函数类型或函数调用不明确(注意 T 可以是函数模板,C++ 允许值作为模板参数)。

同样,使用方括号 T[x]导致数组类型或索引不明确。

我不明白为什么 T{x}还不能用,可能是根本没考虑,也可能是太丑了{…}无处不在。

关于c++ - 为什么 C++ 模板使用尖括号语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43254027/

相关文章:

c++ - 如何将 std::array C++11 操作转换为 Boost+VS08?

c++ - RegCloseKey() 函数应该只在成功调用 RegOpenKey() 之后使用,还是无条件使用?

python - 来自 Python 中另一个实例的实例

c++ - 更简单的 C++ STL 迭代器实例化

c++11 - 递归变量声明

python - 为什么 Julia 不能超集 python?

c++ - 使用 std::for_each 并在 std::set 上绑定(bind)成员函数,代码无法编译

c++ - 在 C++ 复制省略期间如何管理内存?

language-features - 某些编程功能何时以及以何种语言引入?

c# - c# 是否有任何语句不遵循从左到右的评估顺序?