gpt4 book ai didi

c++ - 模板参数不明确 : could not deduce template argument

转载 作者:可可西里 更新时间:2023-11-01 16:30:04 26 4
gpt4 key购买 nike

我正在做一些看起来像这样的包装器:

#include <iostream>

template<class T, class Value>
void Apply(void (T::*cb)(Value), T* obj, Value v)
{
(obj->*cb)(v);
}

class Foo
{
public:
void MyFunc(const int& i)
{
std::cout << i << std::endl;
}

const int& GetValue()
{
return i_;
}

private:
int i_ = 14;
};

int main()
{
Foo f;
Apply(&Foo::MyFunc, &f, f.GetValue());
}

我收到这个错误:

  • 应用:未找到匹配的重载函数。
  • void Apply(void (__thiscall T::* )(Value),T *,Value):模板参数 Value 不明确,可能是 int const int &
  • void Apply(void (__thiscall T::* )(Value),T *,Value):无法从 const 中推断出 Value 的模板参数整数

所以我知道它来自模板参数推导,但我不明白如何。为什么 Value 不会两次都计算为 const int&

最佳答案

为什么会失败

目前,模板参数Value在对 Apply 的调用中在两个不同的地方推导出来: 从指向成员函数参数的指针和最后一个参数开始。来自 &Foo::MyFunc , Value推导为 int const& .来自 f.GetValue() , Value推导为 int .这是因为引用和顶级 cv 限定符被删除以进行模板推导。由于参数 Value 的这两个扣除不同,推导失败 - 删除 Apply()来自重载集,因此我们没有可行的重载。

如何修复

问题是 Value在两个不同的地方推导出来,所以让我们防止这种情况发生。一种方法是将其中一个用途包装在非推导上下文中:

template <class T> struct non_deduced { using type = T; };
template <class T> using non_deduced_t = typename non_deduced<T>::type;

template<class T, class Value>
void Apply(void (T::*cb)(Value), T* obj, non_deduced_t<Value> v)
{
(obj->*cb)(v);
}

最后一个参数,v , 类型为 non_deduced_t<Value>顾名思义,这是一个非推导的上下文。所以在模板推导过程中,Value推导为 int const&从指向成员函数的指针(和以前一样),现在我们只需将其插入到 v 的类型中.

或者,您可以选择推导cb作为它自己的模板参数。在哪一点Apply()只是减少到 std::invoke() .

关于c++ - 模板参数不明确 : could not deduce template argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40496968/

26 4 0