我的站点

一个系统软件工程师的随手涂鸦

Date: 十二月 22, 2015

Go语言的new函数

以下摘自The Go Programming Language

Each call to new returns a distinct variable with a unique address:
p := new(int)
q := new(int)
fmt.Println(p == q) // “false”
There is one exception to this rule: two variables whose type carries no information and is therefore of size zero, such as struct{} or [0]int, may, depending on the implementation, have the same address.
The new function is relatively rarely used because the most common unnamed variables are of struct types, for which the struct literal syntax is more flexible.

Since new is a predeclared function, not a keyword, it’s possible to redefine the name for something else within a function, for example:
func delta(old, new int) int { return new – old }
Of course, within delta, the built-in new function is unavailable.

 

C++要点笔记(1)——模板参数中的class和typename

C++中定义函数模板或者类模板,可以使用class来定义模板参数:

template <class T> ...  

也可使用typename来定义模板参数:

template <typename T> ...  

大多数情况下,二者可以交替使用。但有些情况,比如template template parameter只允许classC++1Z已经提交了关于template template parameter允许typename建议,有些编译器已经支持了)。

参考资料:
Use ‘class’ or ‘typename’ for template parameters?
Why does not a template template parameter allow ‘typename’ after the parameter list

typename另一个用法是在模板的定义中(选自The typename keyword (C++ only)):

Use the keyword typename if you have a qualified name that refers to a type and depends on a template parameter. Only use the keyword typename in template declarations and definitions. Consider the following example:

template<class T> class A
{
  T::x(y);
  typedef char C;
  A::C d;
}

The statement T::x(y) is ambiguous. It could be a call to function x() with a nonlocal argument y, or it could be a declaration of variable y with type T::x. C++ compiler interprets this statement as a function call. In order for the compiler to interpret this statement as a declaration, you must add the keyword typename to the beginning of T:x(y). The statement A::C d; is ill-formed. The class A also refers to A and thus depends on a template parameter. You must add the keyword typename to the beginning of this declaration:

typename A::C d;

You can also use the keyword typename in place of the keyword class in the template parameter declarations.

总结一下,typename只能用在模板的定义和声明中。由于编译器不知道模板参数Tx成员是函数还是类型,为了让C++编译器知道这是变量定义和声明,必须加上typename

另外参考Wikipedia

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.

即在模板的定义和声明中,依赖模板参数的dependent只有在可以确定其为type或使用typename修饰时才认定为type

《Expert C programming》中C++笔记(3)

Scope resolution operator

Capture

《Expert C programming》中C++笔记(2)

Class的定义和availability

1

2

《Expert C programming》中C++笔记(1)

面向对象的基本概念:

Capture

Powered by WordPress & Theme by Anders Norén