C ++错误枚举和CRTP

时间:2011-02-16 11:54:03

标签: c++ enums crtp

template<class T>
struct broker
{
    typedef T typeBroker;
    static std::vector<std::string> extractListBroker(const std::string& broker)
    {
        std::vector<std::string> vec;

        if(broker.empty())          
        {
            for(int i=0;i<typeBroker::nbBroker;++i)
                vec.push_back( typeBroker::listBroker[i] );         
        }           
        else
        {
            typedef boost::tokenizer<boost::char_separator<char> > my_tok;

            boost::char_separator<char> sep( ";" );

            my_tok tok( broker, sep );

            for ( my_tok::const_iterator i = tok.begin(); i != tok.end(); ++i )  
                vec.push_back( *i ); 
        } 
        return vec;
    }

        std::string brokerToStr(typename typeBroker::BROKER i) //<--Problem here !!
    {
        return typeBroker::listBroker[i];           
    }
};


struct brokerDisTradable  : broker<brokerDisTradable>{
    std::vector<std::string> listBroker;
    brokerDisTradable()
    {
        listBroker.push_back("BRIDGE1" );
        listBroker.push_back("BRIDGELONDON" );
        listBroker.push_back("RECY" );
        listBroker.push_back("CURRENEX" );
    }
    static const int nbBroker = 2;
    enum BROKER  { BRIDGE1, BRIDGELONDON, RECY, CURRENEX };
};

错误:错误C2039:'BROKER':不是broker_def :: brokerDisTradable的成员'

任何想法?

谢谢!

5 个答案:

答案 0 :(得分:4)

您不能在基类的函数声明中使用派生类型的内部类型,因为派生类型的内部类型尚未已定义,派生类型仅声明

有很多方法可以解决这个问题,包括类型特征参数和其他模板参数,它们在 Base中使用Derived中定义的类型,在一个奇怪的重复模板模式中完美讨论 of comp.lang.c ++。moderated http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/a99148265cb43680/b2581e058ffe8c91?#b2581e058ffe8c91

答案 1 :(得分:1)

由于您使用枚举值作为数组的索引,因此可以将参数类型更改为brokerToStr为int:

struct broker
{
    typedef T typeBroker;

    std::string brokerToStr(int i)
    {
        return typeBroker::listBroker[i];           
    }

此外,typeBroker::listBroker[i]无效,因为listBroker不是静态成员。

答案 2 :(得分:1)

我不明白为什么要从brokerDisTradable继承border<brokerDisTradable>。可能你需要做的是:

struct brokerDisTradable {
    std::vector<std::string> listBroker;
    brokerDisTradable()
    {
        // ...
    }
    static const int nbBroker = 2;
    enum BROKER  { BRIDGE1, BRIDGELONDON, RECY, CURRENEX };
};

int main() 
{ 
  brokerDisTradable t;
  broker<brokerDisTradable> b;
  // ...
  return 0;
}

答案 3 :(得分:1)

问题的简化示例:

template <class T>
struct X
{
    void foo(typename T::Enum);
};

struct Y: X<Y>  //<-- X instantiate here, but at this point the compiler only knows
                //that a struct called Y exists, not what it contains
{
    enum Enum {Z}; 
};

作为一种可能的解决方法,可能将枚举移出Y并将模板参数添加到X.

template <class T, class EnumType>
struct X
{
    void foo(EnumType);
};

enum Y_Enum {Z};

struct Y: X<Y, Y_Enum>
{  
};

答案 4 :(得分:0)

brokerDisTradable : broker<brokerDisTradable>似乎是一种不完整的类型(内部无限遗产)

struct brokerDisTradable并使用broker<brokerDisTradable>将有效..