I am attempting to create a wrapper around an std::function
for reasons not explained here. I know that the following code works.
std::function<void()> function = [&]() -> void {};
The following is my wrapper around the std::function
, however, it does not work when I try to construct it with a lambda.
template<typename Type, typename ...Args>
class custom_function {
public:
using function_type = std::function<Type(Args...)>;
custom_function(const function_type &other) {
function = other;
}
private:
function_type function;
};
// error: conversion from 'main()::<lambda()>' to non-scalar type 'custom_function<void>' requested
custom_function<void> function = [&]() -> void {
};
I thought that this would work since a lambda can be assigned to a std::function
. If I add the following constructor, the code now compiles.
template<typename Type, typename ...Args>
class custom_function {
// ...
template<typename Lambda>
custom_function(const Lambda &other) {
function = other;
}
// ...
};
// this is now valid
custom_function<void> function = [&]() -> void {
};
Why does this constructor work but the previous constructor did not? Why is...
custom_function(const function_type &other) {
function = other;
}
different from...
template<typename Lambda>
custom_function(const Lambda &other) {
function = other;
}
I'm compiling with C++17 using G++ on Windows. Thanks