开发者

D mixins with string switch statements

开发者 https://www.devze.com 2023-03-24 06:04 出处:网络
I have a D mixin that I\'d like to use to generate a switch statement (case values, specifically) on string values, but despite KeyValues having entries in it and providing the right key values, the d

I have a D mixin that I'd like to use to generate a switch statement (case values, specifically) on string values, but despite KeyValues having entries in it and providing the right key values, the default case is always the only one executed:

class DataStore(KeyValues...) {
    void stringSetData(string key, string data) {
        switch(key) {
            foreach(D; KeyValues) {
                mixin("case \"" ~ D.Name ~ "\": set(to!(D.Type)(data)); break;");
            }
            default:
                throw new Exception("Invalid meta key"); break;
        }
    }
}

I've tested this with hard-coded values, and it works as expected, so my suspicion is that开发者_StackOverflow社区 I might be doing something wrong with my mixin itself. How can I get this to work as expected?


The break inside the mixin is breaking from the foreach loop, not the switch. Replace it with return, or a labelled break.

By the way, if you try to compile this code with warnings enabled, you get some weird error messages from DMD.

0

精彩评论

暂无评论...
验证码 换一张
取 消