【问题标题】:boost::enable_if_c error: is not a valid type for a template non-type parameterboost::enable_if_c 错误:不是模板非类型参数的有效类型
【发布时间】:2016-01-19 20:28:31
【问题描述】:

我想禁止为具有特定类型特征的类型实例化类模板 (PointCloud)。在以下示例中,我只想允许使用定义了 is_good 的类型:

#include <boost/core/enable_if.hpp>

class PointType1 {};

class PointType2 {};


template <typename T>
struct is_good
{
  static const bool value = false;
};

template <>
struct is_good<PointType1>
{
  static const bool value = true;
};

template <typename TPoint, typename boost::enable_if_c<is_good<TPoint>::value>::type = 0>
class PointCloud
{
};


int main()
{
  PointCloud<PointType1> pointCloud1;

  //PointCloud<PointType2> pointCloud2;

  return 0;
}

错误是:

error: 'boost::enable_if_c<true, void>::type {aka void}' is not a valid type for a template non-type parameter
   PointCloud<PointType1> pointCloud1;
                        ^

据我了解,enable_if_c 应该将 ::type 定义为 TPoint,如果 is_good&lt;TPoint&gt;::valuetrue。如果是false,那么::type没有定义,所以SFINAE应该启动。我还以为typename会表明这确实是一个类型参数。

谁能解释为什么会这样?

【问题讨论】:

    标签: c++ templates boost sfinae enable-if


    【解决方案1】:

    当您实例化 PointCloud&lt;PointType1&gt; 时,is_good&lt;TPoint&gt;::valuetrue 并且 boost::enable_if_c&lt;is_good&lt;TPoint&gt;::value&gt;::typevoid

    如错误消息所述,void 不是 non-type template parameter 的有效类型。

    要修复错误,请为 enable_if_c 指定第二个类型参数,而不是使用默认参数 void

    template <typename TPoint,
              typename boost::enable_if_c<is_good<TPoint>::value, int>::type = 0>
                                                                ^^^^^
    

    【讨论】:

    • 但这是一个类型模板参数,不是吗?就像2 不是非类型模板参数,但typedef anything 是类型模板参数?我想我也不明白这里末尾的 =0 - 在函数模板中,当你什么都不传递给它并且函数没有被添加到重载集时,这只会使参数成为一个虚拟参数,但是对于类模板默认模板参数为0是什么意思?
    • @David 不,这是一个非类型参数。那里的typename 是因为::type 依赖于TPoint(请参阅this),所以你需要告诉编译器它是一个依赖名称。 = 0 是一个默认模板参数,就像函数参数的默认参数一样,这意味着您在实例化类时不必指定模板参数。
    • 那为什么是非类型参数呢?在您的示例中,它的计算结果为“int”,这是一种类型,对吧?
    • @DavidDoria 是的,但它不是一组无限可能的类型,就像template&lt;class T&gt; 一样。如果你写template&lt;int N&gt;,那么N是一个非类型模板参数。不知道它是如何得到这个名字的,但可能是因为另一种是 type 模板参数
    猜你喜欢
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多