【问题标题】:How to make a template function const if the template is true如果模板为真,如何使模板函数为 const
【发布时间】:2014-03-16 19:50:15
【问题描述】:

我有一个带有 bool 模板参数 (is_const) 的类方法,它仅在 is_const 为 false 时调用可变函数(使用静态 if)。我怎样才能告诉 D 编译器使这个函数为 is_const = true 而不是为 is_const = false? 我不想复制粘贴该功能,但我看不到任何其他方法。 (我不能使用 inout,因为它对于 is_const=false 和 is_const=true 的行为确实不同)

【问题讨论】:

  • 我认为复制函数体是唯一的方法。 static if 和 mixin 都只适用于整个声明——它们不能有选择地只对签名添加一点点变化。我还没有发布这个作为答案,因为我不太确定,但几乎可以肯定,到目前为止我尝试过的任何黑客都没有得到任何地方。

标签: templates constants d


【解决方案1】:

您可以添加一个 const 重载来转发到事实上的 const 实现:

class C
{
    void m(bool is_const)() // de-facto const when is_const is true
    {
        static if(!is_const) {/* ... mutate ... */};
    }
    void m(bool is_const)() const if(is_const)
    {
        return (cast() this).m!true();
    }
}

然后,您必须格外小心,不要在设置 is_const 时发生变异。

【讨论】:

  • 是的,这比我尝试的要好(使整个函数体成为字符串混合)。除了本着安全的精神,我会反过来做,让可变的称为不可变的。然后,我将在 m 内调用可变函数的任何地方显式转换“this”(这样如果所有此类转换都用静态 if(!is_const) 包装,则很容易通过眼球验证该函数是 const 正确的)跨度>
  • 不过,抛弃 const 和 mutating 是未定义的行为。
  • 这是否意味着这个解决方案不起作用,我应该回到 mixin 方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
相关资源
最近更新 更多