gpt4 book ai didi

c++ - 歧义时的类型名解析

转载 作者:太空宇宙 更新时间:2023-11-04 15:51:05 25 4
gpt4 key购买 nike

我在玩 Visual Studio 和模板。

考虑这段代码

struct Foo
{
struct Bar
{
};

static const int Bar=42;
};

template<typename T>
void MyFunction()
{
typename T::Bar f;
}

int main()
{
MyFunction<Foo>();
return 0;
}

当我编译这是 Visual Studio 2008 和 11 时,我得到以下错误

错误 C2146:语法错误:缺少“;”在标识符“f”之前

Visual Studio 在这方面是否正确?代码是否违反了任何标准?

如果我把代码改成

struct Foo
{
struct Bar
{
};

static const int Bar=42;
};


void SecondFunction( const int& )
{
}

template<typename T>
void MyFunction()
{
SecondFunction( T::Bar );
}

int main()
{
MyFunction<Foo>();
return 0;
}

它编译时没有任何警告。在 Foo::BLAH 中,如果发生冲突,成员优先于类型

在 G++ 4.2.1 上编辑测试

struct Foo
{
static const int Bar=42;
};


void SecondFunction(const int& x)
{
}

template<typename T>
void MyFunction()
{
int x = Foo::Bar;
}

int main()
{
MyFunction<Foo>();
return 0;
}

编译正常。

struct Foo
{
static const int Bar=42;
};


void SecondFunction(const int& x)
{
}

template<typename T>
void MyFunction()
{
SecondFunction(T::Bar);
}

int main()
{
MyFunction<Foo>();
return 0;
}

给我这些错误

undefined symbol : “Foo::Bar”,引用自: cck498aS.o 中的 void MyFunction()ld:未找到符号collect2: ld 返回 1 退出状态

最佳答案

在 C++ 中,命名实体属于三个不同的本体层之一:类型模板

如果依赖名称属于未知层,则必须告诉编译器它是什么:

  • 如果你什么都不说,它就是一个值。

  • 如果你说 typename,它就是一个类型。

  • 如果你说template,它就是一个模板。

因此 T::Bar 作为 MyFunction 模板中的依赖名称,自动假定为引用一个值,因此 int 成员 Foo::Bar。另一方面,在第一个示例中,typename T::Bar 确实引用了成员 type Foo::Bar

关于c++ - 歧义时的类型名解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8145589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com