如何在类模板中使用functor作为成员? [英] How to use functor as a member in class template?
本文介绍了如何在类模板中使用functor作为成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用仿函数作为类模板中的 std :: function
对象。
I was trying to use a functor as a std::function
object inside a class template. Below is what I have done so far.
//! the functor class template
template<typename T>
struct func
{
void operator ()(T t)
{
std::cout << t << "\n";
}
};
//! the class template that holds a std::function object as a member
template<typename T>
struct Foo
{
std::function<void(T)> bar = func<T>();
};
int main()
{
Foo<int> foo;
return 0;
}
有人抱怨
error: conversion from 'func<int>' to non-scalar type 'std::function<void(int)>' requested
struct Foo
^
是否可以这样做?
推荐答案
您可以将其设置为静态并在class-scope之外进行初始化,也可以在构造函数中对其进行初始化。 。在GCC 4.7.2上进行了测试。
You can either make it static and initialize it outside class-scope, or initialize it in the constructor. Tested on GCC 4.7.2.
template<typename T>
struct Foo
{
static std::function<void(T)> bar;
};
template <typename T>
std::function<void(T)> Foo<T>::bar = func<T>();
编辑
在C ++ 11中,您还可以使用括号初始化:
In C++11, you can also use brace-initialization:
std::function<void(T)> bar { func<T>() };
这篇关于如何在类模板中使用functor作为成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文