Dependent types: template argument failed

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); // Does NOT compile function1<int>(image); // Does compile function2(image); // Does compile return 0; } 

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?

+8
c ++ c ++ 11 type-inference templates
source share
1 answer

What causes a compiler error?

You are using (only) with T in an untyped context: nested qualifier names. That is, you put T inside the name, which simply indicates where the type is. The compiler cannot understand your actual intent and will have to try a lot of T

Is it possible to use the signature function1() without having to manually specify a template argument?

Not really. If you want a more concise way of accessing a smart pointer to an image, you can use an alias template, though:

 template <typename T> using ImagePtr = std::shared_ptr<Image<T>>; 

And write function1 as follows:

 template <typename U> void function1(ImagePtr<U> p) {} 
+7
source share

All Articles