我想像下面的代码一样“过滤”可变参数模板函数的参数包(只需要“过滤”某些类型的变量):
#include <iostream>
#include <utility>
#include <cstdlib>
struct Z {};
struct test
{
using result_type = void;
template< typename... P >
result_type apply_filter(P &&... _p) const
{
using std::forward;
return operator () (forward< P >(_p)...);
}
template< typename... T >
result_type operator () (std::string const & _s, T &&... _tail) const
{
std::cout << _s << std::endl;
return operator () (std::forward< T >(_tail)...);
}
template< typename... T >
result_type operator () (double const & _x, T &&... _tail) const
{
std::cout << _x << std::endl;
return operator () (std::forward< T >(_tail)...);
}
template< typename... T >
result_type operator () (Z const &, T &&... _tail) const
{
std::cout << "z" << std::endl;
return operator () (std::forward< T >(_tail)...);
}
private :
result_type operator () () const { return; }
template< typename T, typename U >
using is_the_same = std::is_same< typename std::remove_const< typename std::remove_reference< T >::type >::type, U >;
template< typename T >
typename std::enable_if< is_the_same< T, std::string >::value, std::string >::type
forward(T && _s) const
{
return "\"" + _s + "\"";
}
template< typename T >
typename std::enable_if< is_the_same< T, double >::value, double >::type
forward(T && _x) const
{
return _x + 1.0;
}
};
int main()
{
test test_;
double x = 0.0;
std::string s = "s";
Z z;
test_.apply_filter(x, s, z);
return EXIT_SUCCESS;
}
但std::forward
比 . 中的成员函数具有更高的优先级apply_filter
。因此这里没有过滤。
有什么解决方法吗?