Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - How to ensure that the template parameter is a subtype of a desired type?

I have a template class, what I want to do are the following

  1. Make sure that an object is instantiated only if the template parameter passed is a subtype of a desired type
  2. Communicate to the user of the code upfront what is it that the template parameter must satisfy

(1) is sort of taken care automatically in the sense if the template parameter passed does not support some feature that the class uses the code will not compile. But this error may be detected fairly late. I want the checks to be as early as possible. What I also want to accomplish is that it should be obvious rightaway that template parameter that is passed has to be derived from a base type that I provide.

First, is this misguided ? and if not how shall I do this ? (the simplest way please, C++ is still new to me)

Thanks stackoverflow, you have really speeded up my C++ learning rate.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Given some complete type MyBase, the following will yield a compile-time error if T is not derived from MyBase:

#include <boost/type_traits/is_base_of.hpp>
#include <boost/static_assert.hpp>

template<typename T>
class Foo {
    BOOST_STATIC_ASSERT_MSG(
        (boost::is_base_of<MyBase, T>::value),
        "T must be a descendant of MyBase"
    );
    // Foo implementation as normal
};

If you're using a C++03 compiler with TR1, you can use std::tr1::is_base_of instead of boost::is_base_of; if you're using a C++11 compiler, you can use std::is_base_of instead of boost::is_base_of and the static_assert keyword instead of the BOOST_STATIC_ASSERT_MSG macro:

#include <type_traits>

template<typename T>
class Foo {
    static_assert(
        std::is_base_of<MyBase, T>::value, 
        "T must be a descendant of MyBase"
    );
    // Foo implementation as normal
};

N.b. this will yield true_type for privately and ambiguously-derived types, so this is insufficient if what you really need is to treat T as-a MyBase (in most contexts).

Doc links:
Boost.StaticAssert
Boost.TypeTraits


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...