mixin on identifier
Johannes Totz
johannes at jo-t.de
Tue Nov 22 05:12:22 PST 2011
On 22/11/2011 04:57, David Nadlinger wrote:
> Turns out to be surprisingly tricky… A possible solution is:
>
> mixin template StateOne() {
> int value;
> }
>
> mixin template StateTwo() {
> float data;
> }
>
> mixin template MixinAll(T...) {
> static if (T.length > 0) {
> alias T[0] A;
> mixin A;
> mixin MixinAll!(T[1 .. $]);
> }
> }
>
> class StateSet(T...){
> mixin MixinAll!T;
> }
>
> void main() {
> auto s = new StateSet!(StateOne, StateTwo)();
> }
>
> Hope this helps,
> David
Thanks a lot, David!
A new variant of this (notice the func()s):
mixin template StateOne()
{
int value;
void func(int d)
{
value = d;
}
}
mixin template StateTwo()
{
float data;
void func(float d)
{
data = d;
}
}
mixin template MixinAll(T...)
{
static if (T.length > 0)
{
alias T[0] A;
mixin A;
mixin MixinAll!(T[1 .. $]);
}
}
class StateSet(T...)
{
mixin MixinAll!T;
}
int main(string[] argv)
{
auto s = new StateSet!(StateOne, StateTwo)();
s.value = 1;
s.data = 3.1f;
s.func(2); // Error
s.func(4.5f); // Ok
return 0;
}
Error:
main.StateSet!(StateOne,StateTwo).StateSet.MixinAll!(StateOne,StateTwo).MixinAll!(StateTwo).A!().func
at main.d(20) conflicts with
main.StateSet!(StateOne,StateTwo).StateSet.MixinAll!(StateOne,StateTwo).A!().func
at main.d(10)
I suppose I get the error at the first func() call because int is
implicitly convertible to float. Is it really?
Also, I tried to make the mixed-in members private/etc but this does not
seem to have any effect...
> On 11/22/11 1:02 AM, Johannes Totz wrote:
>> On 21/11/2011 23:39, David Nadlinger wrote:
>>> Make T an alias parameter:
>>> class StateSet(alias T) { … }
>>>
>>> David
>>
>> Thanks!
>>
>> I was trying to get to something like this:
>>
>> mixin template StateOne()
>> {
>> int value;
>> }
>>
>> mixin template StateTwo()
>> {
>> float data;
>> }
>>
>> class StateSet(alias T ...)
>> {
>> mixin T;
>> }
>>
>>
>> int main(string[] argv)
>> {
>> StateSet!(StateOne, StateTwo) s = new StateSet!(StateOne, StateTwo)();
>>
>> return 0;
>> }
>>
>>
>> With the docs I got to:
>>
>> template StateSet(alias T, S ...)
>> {
>> class StateSet
>> {
>> mixin T;
>> }
>> }
>>
>> But I have no clue how to expand S into mixin statements.
>>
>>
>>
>>> On 11/22/11 12:38 AM, Johannes Totz wrote:
>>>>
>>>> mixin template StateOne()
>>>> {
>>>> int value;
>>>> }
>>>>
>>>> class StateSet(T)
>>>> {
>>>> mixin T;
>>>> }
>>>>
>>>> int main(string[] argv)
>>>> {
>>>> StateSet!StateOne s = new StateSet!StateOne();
>>>>
>>>> return 0;
>>>> }
>>>
>>
>
More information about the Digitalmars-d-learn
mailing list