开发者

C++ empty class or typedef

I'm currently using something like that in my code:

class B : public A<C>开发者_StackOverflow { };

Wouldn't it be better to use a typedef?

typedef A<C> B;


It depends. If you want A<C> and B to be distinct but related types, B should extend A<C>. If you want them to be identical, you should use a typedef. Can you provide any more context?


It depends on what you want. If you use your different classes to customize your template meta programming than it is better to create B.

If you use inheritance just to reduce typing than it is not an appropriate solution and you have to go with typedef, they were introduced for that.


Most definitely, if the intent is to give a new name to an existing datatype then use a typedef.


It is not exactly the same. For example with typedef you can do this:

typedef A<C> B;
func(B param) {...}
...
A<C> var;
func(var);


Depends of what you want, the effect is not the same.

C++ typedefs are not "strong", which basically means that B and A<C> will be of the same type. If you want to be able to distinguish between the two, use a class.

Various implementations of strong typedef can be found around the web, the boost one for instance.


Well, I assume you are using the empty class to get out of typing A<C> repeatedly. In that case, I think that a typedef is a better idea. At least, that seems to be the way it is done most often.

Let me add that this is just my opinion. People aren't quite agreed on using typedef in general. Although I think that it is quite alright in this case.

After reading Jon Purdy's answer, I'd like to add that you should use inheritance if you need to extend A and not otherwise.


For completeness I want to add another point: With

class B : public A<C> { };

you can easy forward declare B:

class B;
void func(B param);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜