Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

C++ Template based get()

I have a class with several members of "similar" type like:

class Container {

    C1 c1;
    C2 c2;
    C3 c3;
    ....

    template <typename T>
    const T& get() {
        ????
    }
};

The class has a templated method get<T>() which can be used to get a reference to the member of type T - i.e.

Container cont;

const auto& c1 = cont.get<C1>();

to access the c1 member. The current implementation of get<T>() is based on specialization for all the types represented in the Container class. Is there an elegant way to achieve the same without manually implementing the specializations?

question from:https://stackoverflow.com/questions/65939204/c-template-based-get

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is there an elegant way to achieve the same without manually implementing the specializations?

Starting from C++17, if constexpr

template <typename T>
T const & get() const
 {
   if constexpr ( std::is_same_v<T, C1> )
      return c1;
   else if constexpr ( std::is_same_v<T, C2> )
      return c2;
   else if constexpr ( std::is_same_v<T, C3> )
      return c3;
 }

Before C++17... the best I can imagine is the creation of a std::tuple<C1, C2, C3> and the return of the std::get<T>(tuple)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...