【发布时间】:2019-01-23 11:08:34
【问题描述】:
假设我们有一个模板类。像这样的
template<typename T>
class MyTemplateClass {
private:
T _v1, _v2;
public:
MyTemplateClass(T v1, T v2)
{
_v1 = v1;
_v2 = v2;
}
bool Act()
{
return _v1 > _v2;
}
};
//usage
MyTemplateClass<int> test(1, 2);
std::cout << test.Act() << std::endl;
现在我们想将一个仿函数对象/函数指针/lambda传递给他的构造函数,以便我们可以使用它。
我尝试过类似的方法,但出现运行时错误
template<typename T, typename F>
class MyTemplateClass {
private:
T _v1, _v2;
const F& _func;
public:
MyTemplateClass(T v1, T v2, F functor)
:_func(functor)
{
_v1 = v1;
_v2 = v2;
}
bool Act()
{
return _func(_v1, _v2);
}
};
bool isGreater(int a, int b)
{
return a > b;
}
//later
MyTemplateClass<int, std::function<bool(int, int)>> test(1, 2, isGreater);
std::cout << test.Act() << std::endl;
那么我怎样才能实现这个功能呢?有没有办法在不使用 std::function 并且不为我的仿函数对象传递类型名的情况下使其工作? 我想这样使用它
MyTemplateClass<int> test(1, 2, isGreater);
【问题讨论】:
-
取决于您的编译器及其版本,it might be possible to do what you want。如果你可以启用 C++17 模式,那就试试吧。
-
@Someprogrammerdude 它会复制对象并存储对象,尽管 const&?如果是,我将删除我的答案。
-
@MatthieuBrucher 不会的。
-
@Someprogrammerdude 不,我没有。我只能使用 c++11。最好不要使用 std::function
标签: c++ templates lambda stl functor