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
529 views
in Technique[技术] by (71.8m points)

c++ - Is it considered "correct" to use a template for a function/class that only accepts subclasses of a specific class?

Lets say hypothetically that I am making a game and in that game there are spawning points class SpawnArea for monsters' classes that inherit from class Monster. Would it be correct to use a template knowing that I am not expecting just any class and Spawn will only accept a specific subset of classes? I would like to use a template cause it's the only way I'm aware of to pass a class type as argument for the purpose of constructing instances of a specific class. Is there any more elegant way to write a class who's instances are used to construct multiple instances of some other specific class?

I read this:

Make a template accept a specific class/family of classes?

It did not discuss the issue of constructing instances of a specific set of classes.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's quite common, actually almost all templates have certain requirements towards their arguments. Those are usually implicitly clear from how the template parameter is used, but you can improve the error messages by using type traits. In C++11, they are available from the standard library via #include <type_traits>, otherwise look into Boost.TypeTraits.

With C++11, the usage is quite simple when you also use static_assert:

template< typename T >
std::shared_ptr< T > spawn()
{
    // make this the first line in your function to get errors early.
    // also note that you can use any compile-time check you like.
    static_assert( std::is_base_of< Monster, T >::value,
                   "T is not derived from Monster" );

    // the rest of your code follows here.
    // ...
    // return ...;
}

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

...