Operator =和typedefs

时间:2017-01-20 11:11:15

标签: c++ operator-overloading typedef

请考虑以下示例。

Idea是利用重载operator =自动从所需类型(LinkKey或AttrKey)中选择多个函数调用之一。目前,程序员必须决定调用哪一个,哪个容易出错,如果发生,则很难调试。

不幸的是,似乎编译器无法区分调用,因为基类型始终是int(C2535表示这一点)。

有没有机会在不对LinkKey和AttrKey定义做任何事情的情况下完成这项工作,因为这将是一个重大变化?

构建环境是MSVC 2012。

**更新**

已更改为转化运营商。最初我假设分配发生了,但我知道初始化是一种特殊情况。

两个typedef解析为相同基类型的问题仍然存在。

**更新2 **

我会废弃这个,因为显然不能修改类型定义和包含第三方库。

#include <string>
#include <random>

//  This is an example how the legacy interface works. It does not matter what it does internally. This is stuff that shall not be changed if possible.

typedef int LinkKey;
typedef int AttrKey;


class Store
{
public:

    LinkKey LookupLinkKey( std::string key )
    {       
        // random value is good enough for this example
        return rand();
    }

    AttrKey LookupAttrKey( std::string key )
    {       
        // random value is good enough for this example
        return rand();
    }   

};


// This is my extension, that should protect vs. the failureTest shown below

class Key
{
public:
    Key( std::string keystr )
        : m_keystr( keystr )
    {}

    static void SetStore( Store* pStore )
    {
        s_pStore = pStore;
    }

    //LinkKey Key::operator= (  const Key& key )
    //{         
    //  LinkKey lk = s_pStore->LookupLinkKey( key.m_keystr );
    //  return lk;
    //}

    //AttrKey Key::operator= (  const Key& key ) // C2535: 'LinkKey      Key::operator=(const Key&)' member function already defined or declared
    //{
    //  AttrKey ak = s_pStore->LookupAttrKey( key.m_keystr );
    //  return ak;
    //}

    operator LinkKey() const
    {           
        LinkKey lk = s_pStore->LookupLinkKey( m_keystr );
        return lk;
    }

    operator AttrKey() const 
    {
        AttrKey ak = s_pStore->LookupAttrKey( m_keystr );
        return ak;
    }

private:
    std::string& m_keystr;

    static Store* s_pStore;
};

Store* Key::s_pStore;

// Usage
void main( int argc, char* argv )
{
    Store s;
    Key::SetStore( &s );

    LinkKey lk = Key("Link"); // C2440: cannot convert from 'Key' to 'LinkKey'
    AttrKey ak = Key("Attribute"); // C2240: cannot convert from 'Key' to 'AttrKey'


    LinkKey failureTest = s.LookupAttrKey("Foo"); // Ewwwwww...
}

0 个答案:

没有答案