【发布时间】:2017-06-09 19:09:07
【问题描述】:
#include <vector>
#include <functional>
template<class F>
class Foo
{
public:
template <class T>
void std_function(std::function<F(std::vector<T>)> functor)
{
/* something */
}
template <class T>
void func_ptr(F (*funtor)(std::vector<T>))
{
/* something else */
}
};
template<class T, class F>
F bar(std::vector<T>)
{
return F();
}
int main()
{
Foo<double> test;
std::function<double(std::vector<int>)> barz = bar<int, double>;
test.std_function(bar<int, double>); //error 1
test.std_function(barz); //OK 1
test.func_ptr(bar<int, double>); //OK 2
test.std_function(bar<int>); //error 2::1
test.func_ptr(bar<int>); //error 2::2
return 0;
}
问题 1。
Line error 1:我试图将显式实例化的模板函数(bar<int, double>)作为std::function 传递,但这是不合法的。
Line OK 1 :如果我将bar<int, double> 包装成std::function<double(std::vector<int>)> 并传递包装的仿函数,那么它现在是合法的。
Line OK 2 : 如果我通过Foo::func_ptr 传递bar<int, double>,它得到函数指针作为参数而不是std::function,它也是合法的。
我想让 Line error 1 合法。与 Line OK 2 一样,可以在没有任何包装的情况下传递 bar<int, double>(与 Line OK 1 不同)并保持相同的形式。但是,参数类型不同。我想作为std::function 传递,而不是函数指针。
问题 2。
Line error 2::1 and 2::2 :我想在这里实现的是,我希望 Foo 类将 bar 的返回类型推断为其类模板类型F(对于上面的代码,F 是 double)。所以我可以直接传递为bar<int>,而不是bar<int, double>。
但它似乎推演失败,因为即使我通过Foo::func_ptr传递bar<int>,它仍然会产生错误。我怎样才能让这段代码按照我的意图工作?
【问题讨论】:
标签: c++ c++11 templates c++14 function-templates