在定义模板时,始终定义`value_type`是一个好习惯 [英] Is it a good practice to always define `value_type` when we define a template
问题描述
template<typename T>
class Point
{
public:
typedef T value_type;
...
};
我在 book,pp176 。
问题1 > value_type ?
问题2 > 将被使用?
Question2> Where this defined value_type
will be used?
例如:
Point< int> :: value_type
?
推荐答案
它通常只对容器(如 std :: vector
)有意义,因为所有容器都提供 typedef
接口用于访问包含的值( begin
/ end
, > /
back
),虽然这在C ++ 11中已经过时了 auto
和 decltype
。更清楚地说 some_template< typename container :: value_type> ...
It doesn't hurt to have one, but it mostly only makes sense for containers (like std::vector
), as all containers provide this typedef
and a uniform interface for accessing the contained values (begin
/end
, front
/back
), although this has mostly gotten obsolete in C++11 with auto
and decltype
. It's still cleaner to say some_template<typename container::value_type> ...
, though.
这意味着它们可以在通用代码中互换使用(这是为什么这样做的主要原因) )。如果你的 Point
类知道包含的值是什么类型是有意义的,那么 typedef
。正如我所说,它不伤害。但是,我有一种感觉,它对这个特定的例子没有太大的意义。
That in turn means they can be used interchangeably in generic code (the main reason why things were done that way). If it makes sense for your Point
class to know what types the contained values are, well, have that typedef
. As I said, it doesn't hurt. However, I have a feeling that it doesn't make too much sense for that particular example.
这篇关于在定义模板时,始终定义`value_type`是一个好习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!