我想构建一个简单的模板化工厂函数,它只是将一个仿函数作为模板参数,将仿函数参数作为变量。
下面是一些代码。问题是模板化的功能。在编译时我得到了:
$ 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;
}
答案 0 :(得分:1)
尝试
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;
}
或为operator<<
product