템플릿 유형의 매개 변수로 함수를받는 함수
프로그래밍과 C ++에 상당히 익숙하지 않습니다. 템플릿 값이있는 함수 포인터를 인수로 받아들이고 싶은 함수가 있습니다. 내 말은 ...
이 기능이 있습니다.
template<typename... ColumnTypes, typename... ParameterTypes>
void query(std::function<void(bool success, ozo::rows_of<ColumnTypes...>& results)> callback, const
std::string& query, ParameterTypes&& ... parameters);
"ozo :: rows_of"는 다음에 대한 별칭입니다.
template <typename ... Ts>
std::vector<std::tuple<Ts...>>
각 쿼리에 콜백이 제공되기를 원합니다.이 콜백은 다른 유형을 수락 할 수 있어야합니다. 예. "ColumnTypes"
내가 시도한 것 :
void myfunc(bool succeeded, ozo::rows_of<int>& results)
{
//code
}
postgres_caller->query(myfunc, "SELECT length FROM this_table WHERE id > $1 AND id < $2;", 11, 14);
결과:
.cpp:241:26: error: no matching member function for call to 'query'
postgres_caller->query(myfunc, "SELECT length FROM this_table WHERE id > $1 AND id < $2;", 11, 14);
~~~~~~~~~~~~~~~~~^~~~~
.h : 165 : 22 : 참고 : 후보 템플릿 무시 : 'function <void (bool, vector <tuple <type-parameter-0-0 ...>, allocator <tuple <type-parameter-0-0)와 일치 할 수 없습니다. ...>>> &)> '반대'void (*) (bool, std :: vectorstd :: tuple <int, std :: allocatorstd :: tuple <int>> &) 'void PostgresCaller :: query (std :: function <void (bool success, ozo :: rows_of <ColumnTypes ...> & results)> callback, const std :: string & query, ParameterTypes && ... parameters)
나는 또한 람다로 시도했다.
postgres_caller->query([](bool succeeded, ozo::rows_of<int>& results)
{
//code
}, "SELECT length FROM this_table WHERE id > $1 AND id < $2;", 11, 14);
결과:
error: no matching member function for call to 'query'
postgres_caller->query([](bool succeeded, ozo::rows_of<int>& results)
~~~~~~~~~~~~~~~~~^~~~~
.h : 165 : 22 : 참고 : 후보 템플릿 무시 : 'function <void (bool, vector <tuple <type-parameter-0-0 ...>, allocator <tuple <type-parameter-0-0)와 일치 할 수 없습니다. ...>>> &)> '반대'(lambda at .cpp : 241 : 32) 'void PostgresCaller :: query (std :: function <void (bool success, ozo :: rows_of <ColumnTypes ...> & 결과)> 콜백, const std :: string & 쿼리, ParameterTypes && ... 매개 변수) ^
이것이 가능하고 어떻게 할 수 있습니까? 매우 감사. /남자
답변
템플릿 추론은 전달한 정확한 유형에서만 작동하므로 함수 포인터를 전달하면 템플릿이 std::function
해당 함수 포인터를 어떤 종류 로 변환 할지 추론 할 수 없습니다 .
를 사용하는 대신 호출 가능을 템플릿 매개 변수로 만듭니다 std::function
.
template<typename Callable, typename... ParameterTypes>
void query(Callable callback, const std::string& query, ParameterTypes&& ... parameters) {
callback( ... ); // use it like this
}
대부분의 경우 콜백의 서명을 추론 할 필요가 없습니다. 당신이 취할 것으로 기대하는 인수로 그것을 호출하십시오.
이것이 충분하지 않은 경우 콜백의 서명을 추론하는 방법도 있지만 조금 더 장황 해지고 대부분의 경우 실제 목적이 없습니다.