2009-09-20 63 views
3

既然我们知道概念不是C++ 0x的一部分,我正在寻找方法来限制模板函数中的类型。强制模板函数类型的约束,没有C++ 0x概念

这里有两个例子:

如果我们想确保一个给定类型为整数时,我们可以使用:

template <class N> inline int f(const N n) 
{ 
    if ((N)0.1 != 0)    // if type of N is floating-point 
     err() 

    .... 
} 

如果我们想要确保一个给定的类型是无符号整数,我们可以使用:

template <class N> inline int f(const N n) 
{ 
    if ((N)-1 < (N)1)    // if type of N is floating-point/signed-integer 
     err() 

    .... 
} 

我要寻找创造性的方式ŧ检查额外的限制,这会在运行时导致失败,或者在编译时(没有概念和没有RTTI)导致失败。

有什么建议吗?

回答

12

通过使用类型特征,可以在编译时更好地处理您的检查。

第一:

STATIC_ASSERT(std::numeric_limits<N>::is_integer) 

第二:

STATIC_ASSERT(not std::numeric_limits<M>::is_signed) 

看一看在Boost Concept Check LibraryBoost.StaticAssert

2

您可以通过扩展SFINAE来近似受限功能模板。下面是实际与GCC 4.4.1中的C++ 0x模式下编译的例子:

#include <iostream> 
#include <type_traits> 

#define REQUIRES(...) ,class=typename std::enable_if<(__VA_ARGS__)>::type 

template <typename IntType 
    REQUIRES(std::is_integral<IntType>::value) 
> 
inline IntType f(IntType n) { 
    return n; 
} 

int main() { 
    std::cout << f(2) << '\n'; 
    // std::cout << f(3.1415) << '\n'; // won't work 
} 

约SFINAE的好处是,当模板参数推导失败的函数模板不理,也不会成为其中的一部分过载设置。上面的例子利用了C++ 0x将支持函数模板的默认模板参数的事实。在良好的老C++ 98它是这样的:

template <typename IntType> 
inline 
typename boost::enable_if_c<(
    std::numeric_limits<IntType>::is_integer 
),IntType>::type f(IntType n) { 
    return n; 
} 

干杯, 小号

0

要轻松查看继承你也可以做

template <typename T> 
class MyClass 
{ 
private: 
    static ClassA *checkIfTIsA() { return (T *)NULL; } 
};