让我先解释一下我对"魔法"的意思.我将使用Java中的两个示例:
Object类.+为String对象定义了运算符.这意味着不可能在纯(*)Java中实现Object和String类的实现.现在这就是我对"魔术"的意思:要实现这些类,您需要编译器的一些特殊支持.
我一直喜欢C++的是,据我所知,STL中没有这样的"神奇",即可以在纯C++中实现STL.
现在我的问题是:这是真的吗?或者是否有STL的部分无法在纯C++中实现并需要一些"魔术"/特殊编译器支持?
(*)"纯"是指不使用任何类库.
jal*_*alf 40
Like gbjbaanb correctly said, the STL can be implemented in plain C++, without relying on any kind of compiler "magic".
However, if you go digging in the STL source code for your compiler, you'll probably see code that either isn't standard, or which you're not supposed to write yourself.
The STL can be implemented entirely in standard C++, but that doesn't mean compiler writers aren't allowed to improve it occasionally, using compiler-specific extensions. For example, they might insert non-standard code that ensures better error messages, or perhaps works around some flaw in their compiler, or maybe enables special optimizations by using extra features of that specific compiler.
They also consistently use names that you're not allowed to use. For example, template parameters are typically named something like _Type, which, since it starts with an underscore followed by a capital letter, is reserved for the implementation. The standard library is allowed to use them, but you and I are not. So if you were going to write your own STL implementation, you would have to make some minor changes, but that's not because of any magic, just a way to avoid name clashes between the standard library and user code.
Dre*_*all 15
正如其他人所说,STL可以在纯标准C++ 98中实现.没有说的是STL的开发与C++模板机制的开发同时进行,并且在很大程度上推动了某些特性的包含.我相信Argument Dependent Lookup(ADL,又名Koenig Lookup),模板模板参数和默认模板参数都来到C++来服务Stepanov的STL开发.
因此,通过STL,他们将魔力转化为语言本身.很好,标准委员会认识到,如果这些功能对于标准库有用,那么它们对我们其他人也可能有用!
AnT*_*AnT 14
如果STL只表示C++标准库的模板部分,那么完全可以在没有任何"魔法"的情况下实现它.每个给定的实现是否实际上使用任何"魔法"都是一个不同的问题(STL的某些部分"魔术"会有所帮助,但并非绝对必要).
现在,如果你在谈论整个C++标准库,那么它确实有一些"魔力".经典的例子是库提供::operator new和::operator delete实现.我们经常称它们在日常用语中"过载",而形式上它们是可替换的.C++语言不向用户提供此类功能.用户无法编写可替换的功能.
另一个例子是offsetof宏(继承自C标准库).虽然它通常以"纯C"实现,但从迂腐的角度来看,流行的实现实际上是非法的(导致未定义的行为).我还没有看到任何正式的合法实施offsetof,所以我不确定它们是否可能.
另一个例子是(再次,从C继承)用于处理变量参数的宏.它们显然不能用纯C或C++实现.
fre*_*low 10
我很确定有些人type_traits需要编译器魔法,例如has_trivial_constructor,has_virtual_destructor或者is_pod.
C++ 0x将标准化一些事实上的 "魔法"类型特征.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2984.htm
"C++ 0x的其他类型特征"
这包含一些评论,例如"XXXX被认为需要编译器支持".
也可以看看
http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Type-Traits.html#Type-Traits
http://msdn.microsoft.com/en-us/library/ms177194(v=vs.80).aspx