Skip to content

No way to use fn with both const generics and impl Trait #85475

Closed
@E-gy

Description

@E-gy

Say we have a function that uses both const generics and takes an impl Trait argument

fn const_add<const ARG: u64>(addable: impl std::ops::Add<u64>){
    addable + ARG;
}

The function itself compiles just fine... but there is no way to use it.

Specifying the argument like so

const_add::<5>(10);

does not work since one cannot provide explicit arguments when impl Trait is used [E0632]

error[E0632]: cannot provide explicit generic arguments when `impl Trait` is used in argument position
 --> src/main.rs:6:17
  |
6 |     const_add::<5>(10);
  |                 ^ explicit generic argument not allowed

and if we remove the explicit arguments

const_add(10);

the compiler fairly complains that it doesn't know what value to use for the const generic [E0282]

error[E0282]: type annotations needed
 --> src/main.rs:6:5
  |
6 |     const_add(10);
  |     ^^^^^^^^^ cannot infer the value of const parameter `ARG` declared on the function `const_add`

Workaround: Use explicit arguments instead of impl Trait

fn const_add<A, const ARG: u64>(addable: A)
where A: std::ops::Add<u64>
{
    addable + ARG;
}

and infer them with _

const_add::<_, 5>(10);

TLDR: fn with both const generic and impl Trait itself compiles, but is not useable in any way. Rust Playground

Meta

Tested on both Stable 1.52.1 and Nightly 1.54.0-nightly (2021-05-18 4e3e6db011c5b482d2be) channels, with same results.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions