如何将模板类限制为某些内置类型? [英] How do I restrict a template class to certain built-in types?

查看:213
本文介绍了如何将模板类限制为某些内置类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经讨论了几次,但是我发现的所有解决方案都没有工作,或者基于boost的静态断言。我的问题很简单。我有一个类,我只想允许真正的类型(双和浮动)。我想要一个编译时错误,如果我尝试实例化类与非float或double类型。我使用Visual C ++ 11.这是我试过的:

This issue has been discussed a few times but all the solutions I have found either didn't work or were based on boost's static assert. My problem is simple. I have a class, and I only want to allow real types (double and float). I want a compile-time error if I try to instantiate the class with a type other than float or double. I am using Visual C++ 11. Here is what I have tried:

template <typename RealType>
class A
{
  // Warning C4346
  static_assert(std::is_same<RealType, double>::value || std::is_same<RealType, float>::value);
}


template <typename RealType>
class A
{
  // Error C2062: type 'unknown' unexpected
  static_assert(decltype(RealType) == double || decltype(RealType) == float);
}

任何想法?非常感谢!

推荐答案

我看到的一个解决方案是使用 std :: enable_if 在类型别名。类似:

One solution I've seen is to use std::enable_if in a type alias. Something like:

using value_type = typename std::enable_if<
                    std::is_same<float, RealType>::value ||
                    std::is_same<double, RealType>::value,
                    RealType
                >::type;

value_type c> RealType 正是 float double 。否则,类型是未定义的,并且编译失败。

value_type only exists if RealType is exactly float or double. Otherwise, the type is undefined and compilation fails.

但我警告对类型过于严格。模板是一样强大,因为他们是部分是因为鸭子打字他们的意思是任何类型,可以使用你想使用它的方式,将工作。不允许类型为了不允许类型通常不会获得你,并且可以使事情不那么灵活,因为他们可以。例如,您将无法使用更精确的类型,例如大十进制类型。

I'd warn about being too strict with types, though. Templates are as powerful as they are partly because the duck typing they do means that any type that can be used the way you want to use it, will work. Disallowing types for the sake of disallowing types generally doesn't gain you much, and can make things less flexible than they could be. For example, you wouldn't be able to use a type with more precision, like a big-decimal type.

这篇关于如何将模板类限制为某些内置类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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