1

Assume we have class that depends on two template types one of we specialize in constructor, can we not specialize deducable type?

template <typename T, typename I>
class A {
public:
    A(I i) {

    }
};

int main() {
    A<float, int> a(42); // this works, but we can deduce int from 42

    A<float> aa(42); // doesn't work
    //or
    auto aaa = A<float>(42); // doesn't work
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
Vladyslav Mozhvylo
  • 331
  • 1
  • 2
  • 11

1 Answers1

2

In C++20, you can use alias template deduction like this:

template <typename I>
using A_float = A<float, I>;

int main() {
    A_float a(42);
    auto aa = A_float(42);
}

Try it on godbolt.org: Demo.

Alternatively, you can define a make function and deduce I from the function parameter. Because of copy elision, this is no less efficient than constructing the A directly:

template <typename T, typename I>
auto make_a(I i) { return A<T, I>(i); }

int main() {
    auto a = make_a<float>(42);
}

Try it on godbolt.org: Demo.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153