Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 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 Reply

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...