is it possible to set the default value of std::tr1::tuple?

谁说我不能喝 提交于 2019-12-13 19:26:29

问题


(i'm using Visual C+++ 2010) suppose i have defined a tuple like this:

typedef std::tr1::tuple<
int      //i want to set its default value to 9
, double //i want to set its default value to 3.3
, int    //i want to set its default value to 2
, double //i want to set its default value to -7.2
> Mytuple; 

i can do that in a struct. but i wonder if it is possible to do that in std::tr1::tuple.
Besides, i want to know when shoud i use std::tr1:tuple or struct?

anyone can help me?


回答1:


A tuple is not a magical replacement for a struct. Their purposes are very different. A struct is, first and foremost, a language construct. A tuple is a library construct.

Structs get to have default values because the language says that you can write constructors to give them default values. The language then takes responsibility to call that constructor to initialize the struct. tuple, as a library construct, has no such capabilities, anymore than you can give std::vector<T> a default T that it will always automatically use. You can provide initial values for each member, but you can't give it defaults.

And if you think about it, you wouldn't want to. Imagine if someone could say that every tuple<int, float> was always created with 3 and 54.221. Even if some other code created it that knew nothing about this rule, it would have to be followed, (just as constructors for the type are used everywhere that type is used). Remember: every tuple<int, float> is the same type.

Really, a tuple is a substitute for the inability to perform reflection on a struct and do compile-time iteration over its members. The other main reason they exist is to be able to have compile-time dynamic structures (that is, the ability to create aggregates of types based on compile-time arguments, rather than a static list directly written into a file).

So unless you need to use std::tie (for effectively returning multiple values), iteration over members (ie: call some template function for each member of an object), or some similar specialized code, you should be using a struct.



来源:https://stackoverflow.com/questions/13301863/is-it-possible-to-set-the-default-value-of-stdtr1tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!