我想知道有什么方法可以对模板类设置限制吗?
指定在模板中替换的每个类型必须有特定的祖先(实现一些接口)。
template < class B > //and every B must be a child of abstract C
class A {
public:
B * obj;
int f() {
return B::x + this->obj->f();
}
};就像哈斯克尔中的=>
func :: (Ord a, Show b) => a -> b -> c发布于 2010-06-17 22:10:21
您可以使用use BOOST_STATIC_ASSERT或类似的库来断言对模板参数的限制。
例如:
#include <limits>
#include <boost/static_assert.hpp>
template <class UnsignedInt>
class myclass
{
private:
BOOST_STATIC_ASSERT((std::numeric_limits<UnsignedInt>::digits >= 16)
&& std::numeric_limits<UnsignedInt>::is_specialized
&& std::numeric_limits<UnsignedInt>::is_integer
&& !std::numeric_limits<UnsignedInt>::is_signed);
public:
/* details here */
};编辑:对于您的示例,您可以编写
template < class B >
class A {
BOOST_STATIC_ASSERT(boost::is_base_of<C, B>);
public:
B * obj;
int f() {
return B::x + this->obj->f();
}
};发布于 2010-06-17 22:29:05
未来的C++版本将使用概念(这些概念没有加入到C++11中)来支持这一点。
解决这个问题的一种方法是在虚拟模板参数上使用特殊化:
class C {};
template <class B, class dummy=void>
class A;
template <class B>
class A<B, typename enable_if<is_base_and_derived<C, B> >::type>
{
// class definition here
};
struct D : C {};
A<D> d; // fine
A<int> n; // compile error - undefined class A<B>我已经对enable_if和is_base_and_derived here进行了独立的定义。
发布于 2010-06-18 02:50:00
下面的代码使用static_assert在VC10中运行。我刚看过这个用法,并没有深入研究static_assert的实际作用--也许其他人可以回答这个问题。
#include <type_traits>
class Base
{
};
class Derived : public Base
{
};
class SomeRandomClass
{
};
template<typename T>
class A
{
static_assert(std::tr1::is_base_of<Base, T>::value, "T not derived from Base");
};
int _tmain(int argc, _TCHAR* argv[])
{
argc; argv;
//
// This will compile
A<Derived> a;
//
// This will throw a compilation error
A<SomeRandomClass> b;
return 0;
}编译器的输出是:
1>d:\temp\aaa\aaa\aaa.cpp(25): error C2338: T not derived from Base
1> d:\temp\aaa\aaa\aaa.cpp(41) : see reference to class template instantiation 'A<T>' being compiled
1> with
1> [
1> T=SomeRandomClass
1> ]https://stackoverflow.com/questions/3062331
复制相似问题