Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - 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;
    ...
};

I have seen the above code in the book "C++ in a Nutshell" by Ray Lischner, pp176.

Questions:

  1. Is it a good practice to always add the definition for value_type?
  2. Where will this defined value_type be used?

For example: Point<int>::value_type?

question from:https://stackoverflow.com/questions/9637094/is-it-a-good-practice-to-always-define-value-type-when-we-define-a-template

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

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...