Visual C ++编译器允许dependent-name作为没有“typename”的类型? [英] Visual C++ Compiler allows dependent-name as a type without "typename"?
问题描述
今天我的一个朋友告诉我,下面的代码在他的Visual Studio 2008中编译得很好:
Today one of my friends told me that the following code compiles well on his Visual Studio 2008:
#include <vector>
struct A
{
static int const const_iterator = 100;
};
int i;
template <typename T>
void PrintAll(const T & obj)
{
T::const_iterator *i;
}
int main()
{
std::vector<int> v;
A a;
PrintAll(a);
PrintAll(v);
return 0;
}
我通常使用g ++,它总是拒绝通过第二个PrintAll呼叫。我知道,对于这个问题,g ++是做标准的方式翻译一个模板。
I usually use g++, and it always refuse to pass the second PrintAll() call. As I know, for this problem, g++ is doing the standard way translating a template.
那么,我的知识是错误的,还是VS2008的扩展? p>
So, is my knowledge wrong, or is it a extension of VS2008?
推荐答案
这不是一个扩展。
VC ++从来没有实现两个阶段适当地解释:
VC++ never implemented the two phases interpretation properly:
- 在定义点,解析模板并确定所有非依赖名称
- 在实例化时,检查模板是否生成有效的代码
VC ++从未实现第一个阶段...不方便,因为它意味着它不仅接受不符合的代码,而且在某些情况下它产生完全不同的代码。
VC++ never implemented the first phase... it's inconvenient since it means not only that it accepts code that is non-compliant but also that it produces an altogether different code in some situations.
void foo(int) { std::cout << "int" << std::endl; }
template <class T> void tfoo() { foo(2.0); }
void foo(double) { std::cout << "double" << std::endl; }
int main(int argc, char* argv[])
{
tfoo<Dummy>();
}
使用此代码:
- 兼容的编译器将打印int,因为它是模板定义时可用的唯一定义,并且
foo
不依赖于T
。 - VC ++将打印double,因为它从不打扰第1阶段
- compliant compilers will print "int", because it was the only definition available at the point of definition of the template and the resolution of
foo
does not depend onT
. - VC++ will print "double", because it never bothered with phase 1
差异看起来可能显得很愚蠢,但如果你考虑一个大型程序中包含的数量,将在您的模板代码...和BAM:/
It might seem stupid as far as differences go, but if you think about the number of includes you have in a large program, there is a risk that someone will introduce an overload after your template code... and BAM :/
这篇关于Visual C ++编译器允许dependent-name作为没有“typename”的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!