部分特化 a 的替代方法struct
是使用std::integral_constant
重载:
template<class InputIterator1, class InputIterator2, class OutputIterator>
void GetQuantity(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
double supply, double limit,
std::integral_constant<int, 0>);
这可以通过调度程序调用:
template<int distribution,
class InputIterator1, class InputIterator2, class OutputIterator>
void GetQuantity(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
double supply, double limit)
{
GetQuantity(first1, last1, first2, result, supply, limit,
std::integral_constant<int,distribution>{});
}
可以通过转换序列提供默认实现:
template<int dist>
struct der_int_const : std::integral_constant<int, dist>
{}
template<int distribution,
class InputIterator1, class InputIterator2, class OutputIterator>
void GetQuantity(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
double supply, double limit, der_int_const<distribution>{});
还有另一种方法甚至可以部分专门distribution
化参数(简化):
#include <iostream>
#include <type_traits>
struct X0{};
struct X1{};
template<int distribution, class It,
class U = typename std::enable_if<distribution==0>::type>
void GetQuantity(It, X0={});
template<int distribution, class It,
class U = typename std::enable_if<(distribution>1)>::type>
void GetQuantity(It, X1={});
C++03版本:
#include <boost/type_traits.hpp>
然后使用boost::integral_constant
而不是std::integral_constant
#include <boost/utility/enable_if.hpp>
struct X0{};
struct X1{};
template<int distribution, class It>
typename boost::enable_if_c<distribution==0>::type
GetQuantity(It, X0=X0()){ std::cout<<"0\n"; }
template<int distribution, class It>
typename boost::enable_if_c<(distribution>1)>::type
GetQuantity(It, X1=X1()){ std::cout<<"1\n"; }