编写这段代码的正确方法是什么?
typedef boost::shared_ptr<config_value_c> config_value_ptr;
typedef std::vector<config_value_ptr> config_value_vec;
config_value_vec config;
typeof (config.iterator ()) it = config.iterator ();
我想提取一个指向 config_value_c 类的 boost 指针数组的迭代器。我知道我可以将迭代器指定为 std::vector
我知道 typeof 不是真正的关键字,并且我知道 typeid 但它没有做我想要的事情。
typedef boost::shared_ptr<config_value_c> config_value_ptr;
typedef std::vector<config_value_ptr> config_value_vec;
config_value_vec config;
typeof (config.iterator ()) it = config.iterator ();
I want to extract an iterator to an array of boost pointers to class config_value_c. I know I can specify the iterator as std::vector<config_value_ptr>::iterator but I want to do this in a type-agnostic fashion so if I ever change the vector to a list I don't have to go back and update the code. Is that possible? Thanks.
I know typeof is not a real keyword, and I know of typeid but it doesn't do what I want.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您想要:
下一版本的 C++ 标准 (C++0x) 将允许您执行以下操作:
I think you want:
The next edition of the C++ standard (C++0x) will allow you to do:
我认为你想要这个:
避免构造迭代器,因为它具有未定义的行为。
如果您要编写模板方法,请确保使用
typename
关键字。I think you want this:
Avoid construction of iterator as it has undefined behavior.
If you will be writing a template method make sure you proceed with
typename
keyword.您可以执行以下四件事之一:
1)使用即将到来的 auto 关键字,如已经回答的那样。
2) 为容器 typedef 指定一个通用名称,以便您可以更改其类型,而无需重写其一般用法。
3) 如果您希望容器 typedef 的名称保持特定,那么您可以创建一个迭代器 typedef。
当然,如果您开始需要容器的不同类型的迭代器(const 与非 const、向后与向前等),那么您最终可能会得到多个迭代器类型定义。
4) 不要为此烦恼,因为容器类型可能存在根本差异,您可能无法使用简单的 typedef 来解决这些差异。例如,std::sort 可以与 std::vector 一起使用,但不能与 std::list 一起使用。根据您的代码的功能(或将来可能需要执行的操作),尝试使其真正与类型无关可能会花费比其价值更多的时间。但你必须自己评估一下。
You could do one of four things:
1) Use the upcoming auto keyword, as already answered.
2) Give the container typedef a generic name so that you can change its type without wanting to rewrite general usages of it.
3) If you want the container typedef's name to stay specific, then you could make an iterator typedef.
Of course, if you start needing different types of iterators for the container (const vs non-const, backward vs forward, etc) then you may end up with several iterator typedefs.
4) Don't bother with it, because container types can have fundamental differences that you may not be able to resolve with simple typedefs. For instance, std::sort can be used with std::vector but not std::list. Depending on what your code does (or may need to do in the future), trying to keep it truly type-agnostic may take more time than it's worth. But you'll have to evaluate that yourself.