-
Notifications
You must be signed in to change notification settings - Fork 12
Description
As briefly discussed in shader-slang/slang#6885 (filing an issue here since I intend to eventually implement this and this needs a spec).
These would allow a generic type parameter to optionally conform to some interface. This mechanism also needs to provide some method to check this conformance for a block of code and allow using the related interface in that block.
Copying from Yong He's reply to that issue, one possible syntax for this would be:
// `w` refers to the optional `T:IThing` conformance.
// Internally, `w`'s type is `Optional<SubtypeWitness<T,IThing>>`.
void tryF<T : IThing? as w>(inout T val)
{
if (w)
{
// here the compiler can assume `T:IThing`.
val.f();
}
}While this is fine, I'd like to bring up an alternative syntax for discussion as well:
void tryF<T : IThing?>(inout T val)
{
do
{
// here the compiler can assume `T:IThing`.
val.f();
}
where T: IThing; // this should fail to compile if T doesn't have an optional conformance to IThing
}This syntax:
+ Prevents having to deal with cases like if(w || somethingElse) or if(w1 && w2)
+ Keeps the type declaration in the generic parameter simpler, as it doesn't need to introduce a new variable
- Likely always causes user to write more code
Also, is there any plan to add ? syntax for optional types, like Type? == Optional<Type> in Swift? If so, this would clash with that, since T : IThing? would be ambiguous in that it could either refer to an optional conformance or a type that derives from Optional<IThing> (although, now that I think about this, the latter case seems impossible to occur in legitimate code, so maybe this is OK). Optional conformances could perhaps be denoted with T ?: IThing if this is a real problem.
I'm fine with writing the proposal myself simultaneously to implementing the feature, once there's some rough plan / consensus on how it should work.