【发布时间】:2015-03-15 06:09:28
【问题描述】:
我遇到了这个有趣的解决方案(here 以 here 为例)来创建 std::bind 类型函数,而无需显式放置占位符。
任务
实现一个类似的绑定函数,但不能在绑定调用中放入值(我不需要它。)并添加调用这个新绑定函数以绑定成员指针的能力。
我做了什么
所以我想出了如何使用虚拟 std::function 来获取函数的签名。
我还想出了如何删除向 bins 调用添加值的功能。
所以这是我的代码:
#include <functional>
#include <type_traits>
#include <utility>
template <std::size_t... Is>
struct indices {};
template <std::size_t N, std::size_t... Is>
struct build_indices
: build_indices<N-1, N-1, Is...> {};
template <std::size_t... Is>
struct build_indices<0, Is...> : indices<Is...> {};
template<int I> struct placeholder{};
namespace std{
template<int I>
struct is_placeholder< ::placeholder<I>> : std::integral_constant<int, I>{};
} // std::
namespace detail{
template<std::size_t... Is, class Fn, class... Args>
auto my_bind(indices<Is...>, Fn const &f, Fn *i, Args&&... args)
-> decltype(std::bind(f, &i, std::forward<Args>(args)..., placeholder<1 + Is>{}...)){
return std::bind(f, &i, std::forward<Args>(args)..., placeholder<1 + Is>{}...);
}
}
template<class Ret, class... FArgs, class Fn, class... Args>
auto my_bind(std::function<Ret(FArgs...)>, Fn const&f, Fn *i, Args&&... args)
-> decltype(detail::my_bind(build_indices<sizeof...(FArgs) - sizeof...(Args)>{}, f, &i, std::forward<Args>(args)...)){
return detail::my_bind(build_indices<sizeof...(FArgs) - sizeof...(Args)>{}, f, &i, std::forward<Args>(args)...);
}
#include <iostream>
struct tmp{
void testt(int var1, int var2){
std::cout << var1 << " " << var2 << std::endl;
}
};
int main(){
tmp TMP;
auto f3 = my_bind(std::function<void(int, int)>(), &tmp::testt, &TMP);
f3(22, 23);
}
问题
我尝试将成员指针传递给模板,但出现编译器错误。 (问题似乎与成员指针的传递有关)我尝试了其他传递成员指针的方法,例如描述的here 和here,但是使用这些方法我没有取得任何进展。
以下是错误:
g++ -std=c++11 -Wall -W -pedantic -O2 hello-cpp-world.cc -o hello-cpp-world
hello-cpp-world.cc: In function ‘int main()’:
hello-cpp-world.cc:68:73: error: no matching function for call to ‘my_bind(std::function<void(int, int)>, void (tmp::*)(int, int), tmp*)’
auto f3 = my_bind(std::function<void(int, int)>(), &tmp::testt, &TMP);
^
hello-cpp-world.cc:68:73: note: candidate is:
hello-cpp-world.cc:48:6: note: template<class Ret, class ... FArgs, class Fn, class ... Args> decltype (detail::my_bind(build_indices<(sizeof (FArgs ...) - sizeof (Args ...))>{}, f, (& i), (forward<Args>)(my_bind::args)...)) my_bind(std::function<_Res(_ArgTypes ...)>, const Fn&, Fn*, Args&& ...)
auto my_bind(std::function<Ret(FArgs...)>, Fn const&f, Fn *i, Args&&... args) -> decltype(detail::my_bind(build_indices<sizeof...(FArgs) - sizeof...(Args)>{}, f, &i, std::forward<Args>(args)...)){
^
hello-cpp-world.cc:48:6: note: template argument deduction/substitution failed:
hello-cpp-world.cc:68:73: note: deduced conflicting types for parameter ‘Fn’ (‘void (tmp::*)(int, int)’ and ‘tmp’)
auto f3 = my_bind(std::function<void(int, int)>(), &tmp::testt, &TMP);
^
make: *** [hello-cpp-world] Error 1
问题
- 我正在努力实现的目标是否可能? (虽然我很确定它是)
- 如果是这样,如何解决?
【问题讨论】:
标签: c++ templates c++11 stl variadic-templates