Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Templates 如果模板为true,如何使模板函数常量_Templates_Constants_D - Fatal编程技术网

Templates 如果模板为true,如何使模板函数常量

Templates 如果模板为true,如何使模板函数常量,templates,constants,d,Templates,Constants,D,我有一个带有bool模板参数(is_const)的类方法,它只在is_const为false时调用可变函数(使用静态if)。我如何告诉D编译器使这个函数const for is_const=true而不是is_const=false? 我不想复制粘贴该函数,但我看不到任何其他方法。(我不能使用inout,因为它的行为确实与is_const=false和is_const=true不同)您可以添加一个const重载,转发到实际的const实现: class C { void m(bool i

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

您可以添加一个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
时,您必须格外小心,不要发生变异。

我认为复制函数体是唯一的方法。静态if和mixin都只在整个十分位上起作用-它们不能选择性地对签名添加一点更改。我还没有把这个作为一个答案发布,因为我不太确定,但几乎可以肯定,到目前为止,我尝试过的任何破解都没有得到任何结果。是的,这比我尝试的要好(使整个函数体成为一个字符串混合体)。除非是出于安全的考虑,否则我会用另一种方式,让可变的称为不变的。然后,我将在m中调用可变函数的任何地方显式强制转换“this”(因此,如果所有此类强制转换都使用静态if(!is_const)包装,则很容易通过肉眼验证该函数是否为const正确)丢弃const和mutation是未定义的行为,但是,这是否意味着这个解决方案不起作用,我应该回到mixin方法?