0

I have a template template function CreateClassA that is meant to work with ClassA. I would like to declare CreateClassA like this:

template<typename T, template<typename, typename> class Container, typename alloc = std::allocator<T>>
std::shared_ptr<ClassA<T, Container, alloc>> CreateClassA(size_t size, double dist) {

    return std::make_shared<ClassA<T, Container, alloc>>(size, dist);
};

And then call it like this:

  size_t size = 5;
  std::shared_ptr<ClassA<ObjectB, std::vector>> classA2 = CreateClassA(size, 4.5);

For some reason though, the compiler cannot deduce the template argument types, unless I declare CreateClassA like this:

template<typename T, template<typename, typename> class Container, typename alloc = std::allocator<T>>
std::shared_ptr<ClassA<T, Container, alloc>> CreateClassA(ClassA<T,Container, alloc> classA, size_t size, double dist) {

    return std::make_shared<ClassA<T, Container, alloc>>(size, dist);
};

and call the function like this:

size_t size = 5;
ClassA<ObjectB,std::vector> classA(size,5);
std::shared_ptr<ClassA<ObjectB, std::vector>> classA2 = CreateClassA(classA, size, 4.5);

I don't get why the function cannot deduce the template arguments in the first function implementation and why the classA argument is necessary.

EliSquared
  • 1,409
  • 5
  • 20
  • 44
  • Should probably be `const size_t size = 5` so that the compiler knows that's a fixed value. – tadman May 12 '18 at 21:36
  • 2
    This is a classical case of a non-deducible context. The compiler is trying to deduce the `T` part ot `std::shared_ptr`. However, in order for the deduction to work, it is necessarily to deduce something else entirely, namely the parameters of some other template, that results in the `T` type. This cannot be deduced. See the linked answer for more information. – Sam Varshavchik May 12 '18 at 21:38
  • Constness is irrelevant since the argument is only at runtime ... the real problem is "what is `ClassA`"? – o11c May 12 '18 at 21:39
  • Ah I see. The thing is I thought I had tried this: `std::shared_ptr> classA2 = CreateClassA(size, 4.5);` and it didn't work, but I just retried it and now it does work so context deduction is not necessary. – EliSquared May 12 '18 at 21:45

0 Answers0