Передача ссылок на оболочку функции работает неправильноC++

Программы на C++. Форум разработчиков
Anonymous
Передача ссылок на оболочку функции работает неправильно

Сообщение Anonymous »

У меня есть класс functionWrapper, который должен инкапсулировать функцию.
Он работает нормально, но аргументы невозможно передать по ссылке.
Вот это код:
#include
#include
#include
#include

template
struct function_traits;

// Specialization for function pointers
template
struct function_traits {
using return_type = Ret;
using args_type = std::tuple;
};

// Specialization for std::function
template
struct function_traits {
using return_type = Ret;
using args_type = std::tuple;
};

// Specialization for lambdas and functors
template
struct function_traits : function_traits {};

class functionWrapper {
template
class B;

class A {
public:
template
static auto castToB(F func) {
using ArgsTuple = typename function_traits::args_type;

return castToBImpl(std::make_index_sequence{}, func);
}
virtual ~A(){}
private:
template
static auto castToBImpl(std::index_sequence, F func) {
// Create B with the correct argument types based on the number of arguments
return new B(func);
}
};

template
class B : public A {
public:
std::function function;

template
B(F f) : function(f) {}
virtual ~B(){}
};
private:
A* ptr = nullptr;
public:
template
functionWrapper(F f) {
ptr = static_cast(A::castToB(f));
}
functionWrapper(){}
virtual ~functionWrapper(){
delete ptr;
}
template
void operator()(Args... args) {
if (ptr)
static_cast(ptr)->function(std::forward(args...));
}

};

Использование:
void foo(int& a){
std::cout

Подробнее здесь: https://stackoverflow.com/questions/793 ... -correctly

Вернуться в «C++»