DirectXShaderCompiler icon indicating copy to clipboard operation
DirectXShaderCompiler copied to clipboard

Overloading unary operator +- definition accepted but doesn't work

Open sawickiap opened this issue 1 month ago • 2 comments

Description Following simple compute shader fails to compile:

struct MyFloat {
    float Value;
    MyFloat operator-() {
        MyFloat Result;
        Result.Value = -Value;
        return Result;
    }
};
RWByteAddressBuffer Buf : register(u0);
[numthreads(1, 1, 1)]
void mainCS(uint3 dtid: SV_DispatchThreadID) {
    MyFloat f1;
    f1.Value = 1.0;
    MyFloat f2 = -f1;
    Buf.Store<float>(0, f2.Value);
}

Steps to Reproduce Compile the shader with command line:

dxc.exe -T cs_6_0 -E mainCS -Fo MyCS.dxil MyCS.hlsl

Actual Behavior

MyCS.hlsl:14:18: error: scalar, vector, or matrix expected
    MyFloat f2 = -f1;
                 ^

It seems that overloading unary operators +MyVar, -MyVar doesn't work. I understand this, but I think in this case it would be better if the compiler reported an error while the operator is defined, not only when I try to actually use it.

Environment

  • DXC version: dxcompiler.dll: 1.8 - 1.8.2502.11 (239921522); dxil.dll: 1.8(1.8.2502.11), as bundled in Windows SDK 10.0.26100.0.
  • Host Operating System: Windows 11 x86-64 25H2 (OS Build 26200.7171)

sawickiap avatar Nov 24 '25 14:11 sawickiap

This should compile with current HLSL, there's no overload resolution issues unlike the compound assignment where the operator method should usually return a reference and care about const qualifier on the method.

for this reason non-unary operators overload just fine, although I must say I've never tried unary.

Ok actually one of our Devs found an interesting thing.

You can define unary operator, but to call it you need to do

f1.operator-();