简体   繁体   English

替代 operator()() 重载? || 直接会员访问

[英]Alternative to operator()() overloading? || Direct member access

I would like to wrap C types into a CPP class for better memory handling.我想将 C 类型包装到 CPP class 中,以便更好地处理 memory。 For instance the below code snippet shows roughly what I would like to do:例如,下面的代码片段大致显示了我想做的事情:


class TJCompressor
{
public:
    TJCompressor()
        : m_tjInstance(tjInitCompress())
    {
        if (m_tjInstance == nullptr)
            throw std::runtime_error("Could not create a TJ compressor instance");
    }
    ~TJInstance()
    {
        tjDestroy(m_tjInstance);
    }

    const tjhandle& operator()() const
    {
        return m_tjInstance;
    }

private:
    tjhandle m_tjInstance = nullptr;
};

However, now I need to access the actual tjhandle through operator()() and I would prefer to get rid of this.但是,现在我需要通过operator()()访问实际的 tjhandle,我希望摆脱它。

TJCompressor compressor;
tjDecompressHeader3(decompressor(), ... );  // works as expected
tjDecompressHeader3(decompressor, ... );    // preferred way of doing it

I am pretty sure that this is achievable but I somehow can't find anything about how to do it.我很确定这是可以实现的,但不知何故我找不到任何关于如何做到这一点的信息。

What you want I think is a conversion operator.... something that looks like我认为你想要的是一个转换运算符......看起来像

operator const tjhandle & () const { return m_tjInstance; }

you will then be able to call your function as然后您就可以将您的 function 称为

tjDecompressHeader3(decompressor, ...)

More information can be found here: https://en.cppreference.com/w/cpp/language/cast_operator更多信息可以在这里找到: https://en.cppreference.com/w/cpp/language/cast_operator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM