简体   繁体   中英

C++ use enum from different template class as function parameter

I got two template classes CarOwner and Truck .

// CarOwner.h
#include "Truck.h"
template<size_t T1, typename T2>
class CarOwner {
public:
    enum MyEnum {
        red = 0,
        green
    }

   void DoSomething();

private:
   Truck<DataContainer<T1,T2>> truck_;   
   MyEnum color;
}

// CarOwner.hpp
template<size_t T1, typename T2>
void CarOwner<T1,T2>::DoSomething(){
    this->truck_.setEnum(this->color);
}

// Truck.h
template<typename G>
class Truck {
    void setEnum(CarOwner<T1,T2>::MyEnum color); // <---
}

My problem is to understand how to write the function declaration of void setEnum(); . As shown in the code above I actually want to pass the function an enum of type CarOwner<T1,T2>::MyEnum color . As I need to #include "Truck.h" in class CarOwner , I can't include the CarOwner in the Truck class. Furthermore, the template parameters T1 and T2 are unknown inside class Truck as it has a different template type G .

I have no clue how to properly declare this function to accept the CarOwner<T1,T2>::MyEnum . Any help is appreciated!

Edit: template parameter G is a combination of T1 and T2 .

This code is just an example to state my problem and the design obviously is odd.

assuming Truck is instantiated as Truck<DataContainer<T1,T2>> , you can write a partial specialization:

template<typename G>
class Truck {
    // whatever
};

template<typename T1,typename T2>
class CarOwner;

template<typename T1, typename T2>
class Truck<DataContainer<T1,T2>> {
    void setEnum( typename CarOwner<T1,T2>::MyEnum color );
};

alternatively, you could templatize setEnum over, say, OwnerType:

template<typename G>
class Truck {
  template<typename OwnerType>
  void setEnum( typename OwnerType::MyEnum color);
};

// ...

void CarOwner<T1,T2>::DoSomething(){
  this->truck_.template setEnum<CarOwner<T1,T2>>(this->color);
}

or ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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