Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Turning a BOUNDED std::list<class> of parameters into a type std::tuple<class,class,class> tup<classObj1, classObj2,classObj2>

I have a class

class C
{
public:
    C() {}
private:
    int timesTriggered_;

    std::map<std::string, std::tuple<std::string, int, int, int, int, int>> mapST;
    std::vector<std::string> sv;
};

and some objects of this type:

C c1;
C c2;
C c3;

I have a map indexed by strings of class C

std::map<std::string, std::list<C>> cMap;

I add some objects of class C into a map

cMap["1"].push_back(c1);
cMap["2"].push_back(c2);
cMap["3"].push_back(c3);

I need a function that when passed the std::list will return (for example with three elements) an

std::tuple<C&, C&, C&>(c1, c2, c3)

Even though this needs to return an std::tuple, the items of the tuple are always of the same type, C. This has to work no matter how many items in the list there are, although an upper bound of the number of C objects at compile time is fine. So in essence this turns a list (with an upper bound on the number of elements) into a variadic tuple.

Here is a function that returns what I need:

template <typename... Obs> std::tuple<Obs &...> BindObservers(Obs &... obs)
{
    return std::tuple<Obs &...>(obs...);
}

And it is called like this:

auto obs2 = BindObservers(c1, c2, c3);

The problem is that to use BindObservers I need to know the number of parameters being passed to it, the things between the commas. I wish there was a BindObservers that worked like this:

auto obs2 = BindObservers(std::list<C>);

And obs2 would look like (pseudo-code):

std::tuple<C,C,more Cs here to the length of std::list<C>>(one parameter for each item in std::list<C> seperated by commas)

So it is a kind of template meta-programming.

I need it to work with c++11 since I don't have a c++14 compiler.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

A list has an undetermined number of elements at compile time.

A tuple has a known number of elements at compile time.

Therefore there is no way for the compiler to deduce the number of elements in the tuple (as it requires information about the elements of the list which is only known during run time).

Try rephrasing a new question with an example with some integers to show what you want to achieve.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...