How to `decltype` a functors operator()?

How to `decltype` a functors operator()?

本文关键字:operator to decltype How functors      更新时间:2023-10-16

我想构建一个简单的模板工厂功能,它只是将函子作为模板参数,而函数参数为变量。

以下一些代码。问题是模板函数。编译时,我得到了:

$ clang++ -std=c++14 test.cpp -o test
test.cpp:32:16: error: no matching function for call to 'factory'
  std::cout << factory<variance_product_producer>(1.0) << std::endl;
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.cpp:24:28: note: candidate template ignored: substitution failure [with T = variance_product_producer]: call
      to non-static member function without an object argument
decltype(&T::operator()()) factory(Args... args) {
             ~~~~~~~~      ^
1 error generated.

我应该更改它以使其运行?代码:

struct product
{
  int i = 0;
};
struct complex_product_producer
{
  complex_product_producer(float _setting)
  : setting_(_setting)
  {
  }
  product operator()()
  {
    product p;
    p.i = 10;
    return p;
  }
  float setting_;
};
template<typename T, typename... Args>
decltype(&T::operator()()) factory(Args... args) {
  T t(args...);
  return t();
}
#include <iostream>
int main()
{
  std::cout << factory<complex_product_producer>(1.0) << std::endl;
}

尝试

template<typename T, typename... Args>
auto factory(Args... args) -> decltype(T{args...}()) {
  T t{args...};
  return t();
}

但更改main()如下

int main()
{
  auto p = factory<complex_product_producer>(1.0f);
  std::cout << p.i << std::endl;
}

或为product

定义operator<<