首页 > 解决方案 > 模板函数可以访问不完整类型的字段吗?这是有效的吗?

问题描述

我将尝试尽可能清楚地描述这一点。如果您只有前向声明,通常您无法访问结构的内部数据字段。它将给出编译器错误,因为结构的完整定义尚不清楚(不完整类型)。

然而,我在下面制作的最小示例似乎表明模板函数可以在结构仍然是不完整类型时访问它:

#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)上进行了尝试,它们都编译和运行没有问题,所以我只是想我应该检查一下。

作为一个注释,我知道模板函数可以在结构之前定义,因为模板可以对任何替换为模板参数的类型进行操作。令我惊讶的是,我从一个它仍然不知道结构的地方调用模板函数。此时它是一个不透明的指针。

非常感谢!

标签: c++templatesstructforward-declaration

解决方案


推荐阅读