c++ 返回类型的自动模板参数推导失败

72qzrwbm  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(142)

我有一个模板函数

template <typename B, typename A>
B func(A x) {/*do something*/}

在我的代码中,我正在做类似于

uint32_t a[6] = {1,2,3,4,5,6};
uint64_t b = func(a);

但这失败与

test.cxx:10:16: error: no matching function for call to 'func'
  uint64_t b = func(a);
               ^~~~~~~~~
test.cxx:5:6: note: candidate template ignored: couldn't infer template argument 'B'

因此,似乎a的类型是自动推导的,但b的类型不是。我可以指定它(uint64_t b = <uint64_t>func(a);),当然,但为什么编译器不能推导出它?

编辑

下面的评论也发布了函数的内容(实际上是接受了2个其他参数)

template <typename B, typename A>
B bit_slice(A words[], int start, int end) {
  int wordSize = sizeof(A)*8;
  B s = 0;
  int n = end / wordSize;
  for(int i= 0; i <= n; ++i){
    s = (s << wordSize) + words[i];
  }
  s >>= (n+1) * wordSize - (end+1);
  B mask = (((T)1) << (end - start + 1))- 1;
  s &= mask;
  return s;
};

所以基本上是一个数组的位切片(表示某些东西)。

tyg4sfes

tyg4sfes1#

如果参数不能从func(a);推导出来,那么它就不能被推导出来。auto返回类型可以从return语句中推导出来,但这里不能。您将返回值赋给什么并不重要。它根本不像这样工作。
但是,它可以使用模板转换:

#include <iostream>
#include <cstdio>

template <typename A,typename B>
A the_implementation(B x) { return x*2; }

template <typename B>
struct proxy {
    B b;
    template <typename A>
    operator A() {
        return the_implementation<A>(b);
    }
};

template<typename B>
proxy<B> func(B x) {
    return {x};
}

int main() { 
    int x = 42;
    int y = func(x);
}

func返回一个proxy<B>B是从x推导出来的。然后proxy<B>可以通过其转换运算符转换为int,该转换运算符调用实际的函数(因为现在只推导出AB)。
但是,我怀疑上面的代码是否是一个好主意。考虑改为写:

auto b = func<uint64_t>(a);

相关问题