既然我们已经知道概念不是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)失败。
有什么建议吗?
发布于 2009-09-20 14:19:41
通过使用类型特征,在编译时可以更好地处理检查。
第一项:
STATIC_ASSERT(std::numeric_limits<N>::is_integer)第二部分:
STATIC_ASSERT(not std::numeric_limits<M>::is_signed)看看Boost概念检查库和Boost.StaticAssert。
发布于 2009-09-20 16:45:20
您可以通过扩展的SFINAE近似限制函数模板。下面是一个在C++0x模式下使用GCC 4.4.1编译的示例:
#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;
}干杯,S
发布于 2009-09-20 18:41:12
要方便地检查继承,您也可以这样做。
template <typename T>
class MyClass
{
private:
static ClassA *checkIfTIsA() { return (T *)NULL; }
};https://stackoverflow.com/questions/1451103
复制相似问题