In my code, I use the Image<T> template image in combination with std::shared_ptr . It is assumed that these image pointers are transmitted to various image processing functions, some of which are independent of the type of image. Consider the following definition of Image<T> and two processing function1() and function2() .
#include <memory> template <typename T> struct Image { typedef std::shared_ptr<Image<T>> Ptr; }; template <typename T> void function1 (typename Image<T>::Ptr image) {} template <typename T> void function2 (std::shared_ptr<Image<T>> image) {}
Although function1() and function2() effectively have the same signature, function1() easier to read and hides details of how the pointer is implemented. However, I cannot call function1() without explicitly specifying the type of the template. Consider the following code:
int main (void) { Image<int>::Ptr image = std::make_shared<Image<int>>(); function1(image);
If the first call results in a compilation error:
example.cc: In function 'int main()': example.cc:18:19: error: no matching function for call to 'function1(MyClass<int>::Ptr&)' example.cc:18:19: note: candidate is: example.cc:10:6: note: template<class T> void function1(typename MyClass<T>::Ptr) example.cc:10:6: note: template argument deduction/substitution failed: example.cc:18:19: note: couldn't deduce template parameter 'T'
My question is this: is it possible to use the signature function1() without having to manually specify a template argument? What causes a compiler error?
I suspect the problem is because Image<T>::Ptr is a dependent type. Thus, the compiler cannot know the exact definition of this field at compile time. Is it possible to tell the compiler that there will be no specializations of this field in the spirit of the typename keyword, which tells the compiler that the field is a type?
c ++ c ++ 11 type-inference templates
crazypeter
source share