在这个回应中:
这个程序是给出的:
std::vector<int> vi{ 0, 2, 4 };
std::vector<std::string> vs{ "1", "3", "5", "7" };
for (auto i : redi::zip(vi, vs))
std::cout << i.get<0>() << ' ' << i.get<1>() << ' ';
Run Code Online (Sandbox Code Playgroud)
我不知道它的类型auto i
是什么,使得重用专业知识和从示例中学习变得更加困难.以下是改变auto i
成char i
收益
In function ‘int main()’:|
/data/cbworkspace/TestZip/TestZip.cpp|14|error: cannot convert ‘boost::iterator_facade<boost::zip_iterator<boost::tuples::tuple<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, __gnu_cxx::__normal_iterator<int*, std::vector<int> > > >, boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >, boost::random_access_traversal_tag, boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >, long int>::reference {aka boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >}’ to ‘char’ in initialization|
/data/cbworkspace/TestZip/TestZip.cpp|14|warning: unused variable ‘i’ [-Wunused-variable]|
||=== Build finished: 1 errors, 1 warnings (0 minutes, 0 seconds) ===|
Run Code Online (Sandbox Code Playgroud)
试着从中找出类型.
有没有办法弄清楚一个变量的类型auto
在C++ 11中是什么?更清楚的是,我有这样一个struct
:
struct EventData
{
// return value from redi::zip<std::vector<PriceQuote>, std::vector<PriceQuote>> what goes here????? So REDI::Zip is zipping PriceQuote, PriceQuote of bids and asks.
};
struct PriceQuote
{
double price;
double size;
};
Run Code Online (Sandbox Code Playgroud)
nio*_*nio 15
尝试将auto更改为char并阅读错误消息.
Jon*_*ely 10
为什么要将该类型放在结构中?这不是真正的设计得像是要使用的(我应该知道,我写的!),但如果需要,您可以使用decltype
并std::declval
确定型(这仍然会得到正确的答案,如果我改变的实施redi::zip
)
struct EventData
{
// type returned by redi::zip
typedef decltype(redi::zip(std::declval<V1>(), std::declval<V2>())) zipper_type;
// type referred to by zipper_type::iterator
typedef std::iterator_traits<zipper_type::iterator>::value_type zipped_type;
zipper_type m_zipper;
};
Run Code Online (Sandbox Code Playgroud)
NB你为什么要创建typedef
的struct
?这是C++而不是C,停止它.
我不知道auto i的类型是什么,使得重用专业知识和从示例中学习变得更加困难.
习惯它.你知道std::bind
返回的类型吗?你知道std::mem_fn
返回的类型吗?你知道lambda表达式创建的类型吗?不,您不需要知道,您需要知道的是它具有哪些属性以及您可以使用它做什么,而不是它的名称或它包含的类型.
你找到了吗?
for (boost::iterator_facade<
boost::zip_iterator<
boost::tuples::tuple<std::vector<int>::iterator,
std::vector<int>::iterator>
>,
boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >,
boost::random_access_traversal_tag,
boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >,
long int
>::reference i : redi::zip(vi, vs))
std::cout << i.get<0>() << ' ' << i.get<1>() << ' ';
Run Code Online (Sandbox Code Playgroud)
更容易理解?
一个答案
“如何在编译时确定“自动”变量的实际类型”
尝试编译这样的东西:
auto foo = function_that_returns_unknown_type() // "what type could foo be?"
int a = foo;
Run Code Online (Sandbox Code Playgroud)
编译器错误消息将告诉您“类型XXX
(无论是什么)无法转换为int
”。那里有你的类型