【问题标题】:using typedef with template将 typedef 与模板一起使用
【发布时间】:2015-04-10 16:30:36
【问题描述】:

taken from here 下面的代码(并稍作修改)使用 g++ 编译器产生以下错误消息: 错误:“typedef”的模板声明 /RangeChecks.hpp:145:12:错误:“IsInRange”没有命名类型

以下是我的 RangeChecks.hpp 文件中的相关部分:

class GreaterEqual
{
  public:
     template <class T>
     static bool Compare (const T& value, const T& threshold)
     {
        return !(value < threshold); /* value >= threshold */
     }
};

class LessEqual
{
  public:
     template <class T>
     static bool Compare (const T& value, const T& threshold)
     {
        return !(value > threshold); /* value <= threshold */
     }
};

template <class L, class R, class T>
bool IsInRange (const T& value, const T& min, const T& max)
{
     return L::template Compare<T> (value, min) && R::template Compare<T> (value, max);
}

typedef IsInRange< GreaterEqual , LessEqual > isInClosedRange;

我在互联网上搜索了一个答案,我发现有一些类似的东西,但没有一个解决了我的问题。

【问题讨论】:

  • @myaut 那些别名声明仍然只适用于类型,这是一个函数。

标签: c++ templates


【解决方案1】:

IsInRange 是一个函数,而不是一个类型。做你想做的最简单的方法是编写一个包装器:

template<class T>
bool isInClosedRange(const T& value, const T& min, const T& max) {
    return IsInRange<T, GreaterEqual, LessEqual>(value, min, max);
}

【讨论】:

    【解决方案2】:

    IsInRange 是函数模板,不是类模板,所以它的实例化不是类型,所以不能为它创建 typedef。

    【讨论】:

    • 是否可以将 IsInRange 定义为类模板?这样做有意义吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多