通过基类的C ++模板专门化 [英] C++ template specialization via a base class

查看:169
本文介绍了通过基类的C ++模板专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想能够让编译器喊我调用的foo的构造函数与类
不是从基础派生。当前代码只允许foo< base >本身。任何
简单的解决方案?

I want to be able to make the compiler shout when i call a constructor of foo with a class that is NOT derived from base. The current code allows only for foo<base> itself. Any easy solution ?

class _base
{
public:
    // ...
};

class _derived: public _base
{
public:
    // ...
};

template <typename T>
class foo
{
public:
    foo ()		{ void TEMPLATE_ERROR; }
};

template <> foo<_base*>::foo () 
{
    // this is the only constructor
}

主要代码:

foo<_base*>    a;    // should work 
foo<_derived*> b;    // should work (but doesnt)
foo<int*>      c;    // should not work (and infact doesnt)


推荐答案

Boost您可以使用类似以下内容来确定指针类型是否可以隐式转换为另一个指针类型:

Without Boost you can use something like the following to determine whether a pointer-to-type can be implicitly cast to another pointer-to-type:

template <class Derived, class Base>
struct IsConvertible
{
    template <class T>
    static char test(T*);

    template <class T>
    static double test(...);

    static const bool value = sizeof(test<Base>(static_cast<Derived*>(0))) == 1;
};

为了在编译时触发错误,现在可以使用

To make it trigger an error at compile-time, you can now use value in an expression that causes an error if it is false, for example typedef a negative-sized array.

template <typename T>
class foo
{
public:
    foo ()
    {
        typedef T assert_at_compile_time[IsConvertible<T, _base>::value ? 1 : -1];
    }
};

这篇关于通过基类的C ++模板专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆