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;
}
It was complained that
error: conversion from 'func<int>' to non-scalar type 'std::function<void(int)>' requested
struct Foo
^
Is it possible to do so? How to fix it?
Different ways to use std::function in a non-static data member initializer
Additional question
I tried to find differences between variable brace-or-equal-initializer and the non-static data member brace-or-equal-initializer. I found nothing.
What is the difference between
and
when ENABLE_CONVERSION is zero?
In your case std::function is optional, use direct functor itself.
EDIT: In common case, move template from struct declration to the operator, i.e. as:
in c++14, std::less<>, std::greater<> and more other functors template keyword moved to the operator declaration, instead of struct declaration, it's help more generic comparation.
Edit2: You may use following technicus:
You can either make it static and initialize it outside class-scope, or initialize it in the constructor. Tested on GCC 4.7.2.
EDIT
In C++11, you can also use brace-initialization: