[问题] the C++ programming language里面的问题

楼主: saladim (杀拉顶)   2019-07-02 01:28:24
大家好, 最近刚好翻到the C++ programming language,章节C.13.8.4
有关templates, namespace 跟 specialization的, 看不太懂他所要表达的意思.
首先呢, 上面提到:
.......省略.......
This reflects three obvious strategies an implementation can use for
generating specializations:
[1] Generate a specialization the first time a call is seen.
[2] At the end of a translation unit, generate all specializations needed for
that translation unit.
[3] Once every translation unit of a program has been seen, generate all
specializations needed for the program.
All three strategies have strengths and weaknesses, and combinations of these
strategies are also possible.
......省略.......
然后说:
A program is illegal, if it is possible to construct two different meanings
by choosing different points of instantiation or different contents of
namespaces at different possible contexts for generating the specialization.
然后有一段范例码:
namespace N
{
class A{ /* ... */ };
char f(A,int) ;
}
template<class T, class T2> char g(T t, T2 t2) { return f(t,t2) ; }
//error (alternative resolutions of f(t))
char c= g(N: :A() ,'a') ; //<
作者: CoNsTaR ((const *))   2019-07-02 04:58:00
就只是告诉你编译器可能用的算法,再告诉你不论编译器用的是哪种编出来的一定都是 legal 的程式,然后讲完什么是 illegal 之后举个例给你看
楼主: saladim (杀拉顶)   2019-07-02 23:11:00
可是这样的话 如同在P.S.里面所说的 改成 char f(A,char)之后 specilazation产生在不同位置 可能会呼叫到不同函数不是应该是illegal吗? 但是实际上是可以编译的...那不就代表我使用的compiler其实是用混合策略?不对 想一想还是觉得哪里怪怪的 因为内文是说只要有可能有不同意义(在不同位置产生码) 那程式就属不合法了....
作者: sarafciel (Cattuz)   2019-07-03 02:28:00
因为overload resolution的缘故 你后面加的那个函式会被优先选择 然后会因为没有回传值编译失败所以你把void改char当然就编得过了
作者: CoNsTaR ((const *))   2019-07-03 07:45:00
欸... 不论用哪种策略都不会影响编译成功与否吧,只是有各自的优缺点(他这样讲我猜是最佳化难易度之类的编译时期才有差的优缺点)你的 template 尝试去 instantiate 一个 char f(A, char),但原本就已经有一个 void f(A, char) 了,如果你的编译器允许这个 instantiation 那就会造成有两个不同版本的 f(A, char),显然你的编译器不允许,所以才告诉你编译错误但我想文说的两个不同版本指的也可以是型别完全相同的两个不同 instantiation,但除非你的编译器有 bug 否则没办法借由改变程式码来造成这样的结果,所以才用这种相似的 example 给你看* 两个型别完全相同的 instance
作者: adrianshum (Alien)   2019-07-03 09:12:00
单看这段节录前后两段没直接关系吧?前者在说compiler做specialisation 的策略,后者在说:呐,如果不同位置就产生不同specialisation 的话那就是不合法的code。这与选前一段哪种策略无关。

Links booklink

Contact Us: admin [ a t ] ucptt.com