【问题标题】:C++ conditional giving an errorC ++条件给出错误
【发布时间】:2023-03-03 10:47:01
【问题描述】:

看看这段代码:

#include <iostream>

using namespace std;
using ld = long double;

template<int i>
struct A {
    static_assert(false,"");
    constexpr static int value = 3;
};

template<int i>
struct B {
    constexpr static int value = i*i*i;
};

template<int i>
struct CheckVal {
    constexpr static int value = conditional<i == 1,A,B><3>::value;
};

如果将1 传递给CheckVal,这应该会终止编译,但无论传递给CheckVal 的内容如何,​​我都会在编译时收到以下错误:

error: use of class template 'A' requires template arguments
    constexpr static ld value = conditional<i == 1,A,B><3>::value;

这里有什么问题?我该如何解决?

【问题讨论】:

    标签: c++ templates template-meta-programming


    【解决方案1】:

    您使用A 的唯一地方是conditional&lt;&gt; 内部。

    A 需要一个模板参数,即template&lt;int i&gt;

    因此,您必须说 A&lt;i&gt;A&lt;3&gt; 或 ... 与 B 相同,而不是 A。 最后,您必须删除 &lt;3&gt;,因为您的编译器会告诉您:

    template<int i>
    struct CheckVal {
        constexpr static int value = conditional<i == 1, A<i>, B<i> >::value;
    };
    

    但是,编译器(至少是 g++)会失败

    错误:静态断言失败:
    static_assert(false,"");
    ^

    【讨论】:

      【解决方案2】:

      首先,您的static_assert 将始终触发,所以不确定它的目的是什么。如果您将其注释掉,这就是您需要在 CheckVal 中更改以使其工作的内容:

      template<int i>
      struct CheckVal
      {
          constexpr static int value = std::conditional<i == 1, A<3>, B<3>>::type::value;
      };
      

      std::conditional 将根据条件选择A&lt;3&gt;B&lt;3&gt;,然后您首先需要返回类型::type,然后才能获得::value 成员

      演示:https://ideone.com/tozaYr

      【讨论】:

        【解决方案3】:

        我不太确定您要达到什么目的,但这种简单得多的构造还不够吗?

        template<int i>
        struct CheckVal {
            static_assert(i != 1,"");
        };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-29
          • 2013-12-28
          • 2021-07-31
          • 2017-01-22
          • 2013-10-14
          • 1970-01-01
          • 1970-01-01
          • 2011-12-19
          相关资源
          最近更新 更多