【问题标题】:How to get a member typedef from an object instance如何从对象实例中获取成员 typedef
【发布时间】:2015-05-12 18:54:39
【问题描述】:

在MSVC2010中给出如下代码:
error C2039: 'my_type' : is not a member of ''global namespace''

template<typename T>
class C
{
public:
    typedef T my_type;
};

C<int> c;

auto f = [&c]() { 
    decltype(c)::my_type v2;   // ERROR C2039
};

我找到了一种蹩脚的方法来解决它,但我想知道当你只有一个对象实例时获取 typedef 的正确方法是什么。

【问题讨论】:

  • 升级你的编译器版本或者依赖或者变通办法,我想到的一个是identity&lt;decltype(c)&gt;::type::my_type v2;template &lt;class T&gt; struct identity { typedef T type; };
  • 完美,谢谢!我不确定这是 VC2010 的问题,还是我只是不明白该怎么做。
  • 您也不需要捕获c(如果它是全局的或静态的)。
  • cC&lt;int&gt; 还是 C&lt;int&gt;&amp; 在 lambda 的主体中?虽然捕获全局变量毫无意义,但也许编译器实际上正在这样做?尝试加入衰减或删除参考?
  • @tukra 然后decltype(c) 会是C&lt;int&gt;&amp; 不是吗?并且C&lt;int&gt;&amp;::my_type 没有多大意义(也许它应该可以工作,但我可以看到一个吱吱作响的编译器失败,即使它应该)。试试typename std::remove_reference&lt;decltype(c)&gt;::type::my_type

标签: c++ templates typedef


【解决方案1】:

从一个非常有用的 cmets 集团中,我得到了一个可行的解决方案。感谢大家。 remove_reference 作为身份对象有双重用途。

template<typename T>
class C {
public:
  typedef T my_type;
};

void g() {
  C<int> c;

  auto f = [&c]() {
    typedef remove_reference<decltype(c)>::type::my_type my_type;
    my_type v;   // Works!!
  }; 
}

【讨论】:

  • remove_referenceidentity 都是多余的,只选一个
  • 尽管 MSVC 按原样接受它,但标准要求您在此处使用 typename,即 typedef typename remove_reference&lt;decltype(c)&gt;::type::my_type my_type;
  • @Oberon 类型名不是必需的
  • @PiotrS。我认为是,见stackoverflow.com/questions/4421306/…
  • @Oberon 我相信 typename 只能在模板中使用。
猜你喜欢
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多