【问题标题】:Illegal indirection in C++ templatesC++ 模板中的非法间接寻址
【发布时间】:2013-04-23 20:10:09
【问题描述】:

我有一个模板类,一旦它得到一个string 作为T,另一个Para* 作为T。 我已经为Para 重载了<<

friend ostream& operator<< (ostream &wyjscie, Para const& ex){
        wyjscie << "(" << ex.wrt << ", " << ex.liczbaWystapien <<")"<< endl;
        return wyjscie;
    }

所以要打印它我必须使用cout&lt;&lt;*objectOfClassPara&lt;&lt;endl; 否则我会打印 地址,但我不能为string 这样做。

如何更正此代码udner?

T t = n->key;
            //cout<<n->key<<endl;
            cout<<t<<endl;
            if (is_same<T, Para*>::value){
                cout<<*t<<endl; //IILEGAL INDIRECTION
            }

【问题讨论】:

  • t 不是指针,那你为什么要取消引用它呢?
  • @0x499602D2 因为它有时是......在它下面我们有Para* variable

标签: c++ templates indirection


【解决方案1】:

您的问题是 if 是一个 runtime if 检查,并且所有可能的类型都必须编译,无论代码是否可以实际执行。所以当Tstring 时,* 会导致代码失败。

最简单的解决方案是提供一个重载的operator&lt;&lt;,它与指针一起工作并删除*

ostream& operator<< (ostream &wyjscie, Para const* ex)
{
    return wyjscie << *ex;
}

【讨论】:

【解决方案2】:
T t

不是指针,正如 0x499602D2 提到的那样..

T* t

是一个指针,可以像cout&lt;&lt;*t&lt;&lt;endl;那样解引用模板参数需要是typespointer-to-type是无效的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多