依赖类型:模板参数推断失败

cra*_*ter 8 c++ templates type-inference c++11

在我的代码使用模板图像类Image<T>与组合std::shared_ptr.这些图像指针应该被传递给各种图像处理功能,其中一些功能与图像类型无关.考虑以下定义Image<T>,以及两个处理函数function1()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) {}
Run Code Online (Sandbox Code Playgroud)

虽然function1()并且function2()有效地具有相同的签名,但是function1()更容易阅读并隐藏指针如何实现的细节.但是,我在function1()没有明确指定模板类型的情况下无法调用.请考虑以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

第一次调用导致编译错误:

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'
Run Code Online (Sandbox Code Playgroud)

我的问题如下:是否可以使用签名而function1()无需手动指定模板参数?是什么导致编译器错误?

我怀疑问题是由Image<T>::Ptr一个依赖类型的事实引起的.因此编译器在编译时无法知道该字段的确切定义.是否有可能告诉编译器没有该字段的特化,在typename关键字的精神中告诉编译器字段是一个类型?

Col*_*mbo 7

是什么导致编译器错误?

您(仅)T在非推导的上下文中使用:嵌套名称说明符 s.也就是说,你放入T一个只指定类型所在位置的名称.编译器无法理解你的实际意图,并且必须尝试很多T.

是否可以使用签名而function1()无需手动指定模板参数?

并不是的.如果您想要一种更简洁的方式来引用指向图像的智能指针,您可以使用别名模板:

template <typename T>
using ImagePtr = std::shared_ptr<Image<T>>;
Run Code Online (Sandbox Code Playgroud)

并写下function1:

template <typename U>
void function1(ImagePtr<U> p) {}
Run Code Online (Sandbox Code Playgroud)