1

My problem is similar to When a compiler can infer a template parameter?, but a little more complex.

I want to create a factory function, which deduces the type of its result so that I don't have to write it myself, but use auto instead (as in auto b = ... or auto b3 = ... below).

I can get the code to work with plain pointers, but when I change them to unique_ptrs compiler complains.

Here's the sample code.

#include <iostream>
#include <memory>

template <typename T>
struct A {
    T fA() const { return T(); }
};

struct Aint : A<int> {};

template <typename T>
struct B {
    B(std::unique_ptr<A<T>> ptr) : ptr_(std::move(ptr)) {}
    B(A<T>* ptr) : ptr_(ptr) {}
    std::unique_ptr<A<T>> ptr_;
};

template <typename T>
std::unique_ptr<B<T>> CreateB(A<T>* a) {
    return std::unique_ptr<B<T>>(new B<T>(a));
}

template <typename T>
std::unique_ptr<B<T>> CreateBFromUnique(std::unique_ptr<A<T>> a) {
    return std::unique_ptr<B<T>>(new B<T>(std::move(a)));
}

int main() {
    auto b = CreateB(new Aint);
    std::cout << b->ptr_->fA() << "\n";

    std::unique_ptr<Aint> a(new Aint);
    // call below fails to compile
    auto b2 = CreateBFromUnique(std::move(a));
    // This works fine.
    auto b3 = CreateBFromUnique<int>(std::move(a));
}

Here's clangs output (g++ prints a similar message):

templates1.cpp:34:15: error: no matching function for call to 'CreateBFromUnique'
    auto b2 = CreateBFromUnique(std::move(a));
              ^~~~~~~~~~~~~~~~~
templates1.cpp:24:23: note: candidate template ignored: could not match 'A<type-parameter-0-0>' against 'Aint'
std::unique_ptr<B<T>> CreateBFromUnique(std::unique_ptr<A<T>> a) {
                      ^

How do I create a factory function that compiles here?

PS meta request: what is the canonical way to describe this problem so as to google it easily?

1 Answer 1

0

There's more than one way to do it, of course, but...

#include <memory>

template <typename T> T AtypeHelper(A<T>*){}
template <typename T>
using Atype = decltype(AtypeHelper((T*)0));

template <typename U, typename T = Atype<U>>
  std::unique_ptr<B<T>> CreateBFromUnique(std::unique_ptr<U> a) {
  return MakeUnique<B<T>>(std::move(a));
}

int main() {
    auto b = CreateBFromUnique(MakeUnique<Aint>());
}

... You might also consider exporting a typedef from A<T> to make the T easily extractable as something like typename U::value_type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.