gpt4 book ai didi

c++ - 依赖类型 : Template argument deduction failed

转载 作者:可可西里 更新时间:2023-11-01 17:50:27 28 4
gpt4 key购买 nike

在我的代码中,我使用了模板化图像类 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) {}

同时 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;
}

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

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'

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

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

最佳答案

What is causing the compiler error?

您(仅)在非推导上下文中使用 T:nested-name-specifier。也就是说,您将 T 放在一个仅指定类型所在位置的名称中。编译器无法理解您的实际意图,因此必须尝试很多 T

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

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

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

然后这样写function1:

template <typename U>
void function1(ImagePtr<U> p) {}

关于c++ - 依赖类型 : Template argument deduction failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31541008/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com