【问题标题】:Why can't I access and use a member type aliases from an object?为什么我不能从对象访问和使用成员类型别名?
【发布时间】:2021-04-28 12:02:05
【问题描述】:

是否不可能从该类的对象访问模板化类的类型别名(或typedef)?例如,为什么以下不可能:

template <typename TKey, typename TData>
class MyClass
{
public:
    using key_t = TKey;
    using data_t = TData;
    TKey key;
    TData data;
    MyClass(TKey _key, TData _data) : key(_key), data(_data) {  }
};

int main() {
    MyClass<int, float> mc{1, 1.0f};
    using DataType = typename mc.data_t; //error: expected ';' after alias declaration
    mc.data_t newData = 2.0f; //error: Cannot refer to type member in 'MyClass<int,float> with '.'

    return 0;
}

还有其他方法可以做这样的事情吗?

【问题讨论】:

  • using DataType = MyClass&lt;int, float&gt;::data_t; 适用于第一行。

标签: c++ c++17 type-alias


【解决方案1】:

您的语法错误。将其更改为:

int main() {
    MyClass<int, float> mc{1, 1.0f};
    using DataType = typename MyClass<int,float>::data_t;
    MyClass<int,float>::data_t newData = 2.0f;
    return 0;
}

如果你想直接从mc获取别名,你可以using DataType = decltype(mc)::data_t;。您实际上可以避免任何重复 MyClass&lt;int,float&gt;

int main() {
    MyClass<int, float> mc{1, 1.0f};  
    
    // suppose we cannot or do not want to spell out MyClass<int,float> again...  
    using my_class_t = decltype(mc);
    using data_t = my_class_t::data_t;
    data_t newData = 2.0f;
}

【讨论】:

  • 谢谢,decltype 正是我想要的!
猜你喜欢
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-24
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
相关资源
最近更新 更多