c++ - 模板函数可以访问不完整类型的字段吗?这是有效的吗?
问题描述
我将尝试尽可能清楚地描述这一点。如果您只有前向声明,通常您无法访问结构的内部数据字段。它将给出编译器错误,因为结构的完整定义尚不清楚(不完整类型)。
然而,我在下面制作的最小示例似乎表明模板函数可以在结构仍然是不完整类型时访问它:
#include <string>
template <typename T>
void template_setName(T *t)
{
// Valid, but no struct declaration at this point by the time it is called???
t->name = "Bob";
}
struct User;
void setName(User *u)
{
// Invalid, only have forward declare at this point.
//u->name = "Bob";
// User* is fine as opaque pointer but this following function will
// access a field...
template_setName(u);
}
// Actually declare structure here. No function above should be able to
// access the data.
struct User
{
std::string name;
};
int main()
{
User u;
setName(&u);
return 0;
}
这让我相信这是未定义的行为?也许我正在使用的这个特定编译器恰好在最后从模板生成具体代码,在它全部被声明之后?我已经在每个我可以使用的编译器(g++、clang++、cl、suncc)上进行了尝试,它们都编译和运行没有问题,所以我只是想我应该检查一下。
作为一个注释,我知道模板函数可以在结构之前定义,因为模板可以对任何替换为模板参数的类型进行操作。令我惊讶的是,我从一个它仍然不知道结构的地方调用模板函数。此时它是一个不透明的指针。
非常感谢!
解决方案
推荐阅读
- typescript - How to understand syntax in TypeScript interface [key: string]
- ms-access-2013 - How do you remove duplicate rows in Access?
- git - When does git actually verify the integrity of the commit chain?
- python - 每个 PyCharm 项目中的 venv 目录
- python - Python错误:行继续字符后出现意外字符
- asp.net-core-2.0 - https://github.com/jwaliszko/ExpressiveAnnotations 是否支持 ASP.NET Core 2?
- saml - 设置新的 Shibboleth IdP 以使用现有的 SAML SP
- r - 根据数据框中的不同列填充值
- oracle - Oracle - 从选择中操作数据并返回整个结果的函数
- javascript - 在具有角度的 ngx-leaflet 的 featureGroup 上使用 getBounds/fitBounds