function as template parameter : if(T receive 2 param)T(a,b); else T(a);

徘徊边缘 提交于 2019-12-01 08:25:53

Variadic templates, partial specialization and SFINAE can help you.

If you accept to duplicate the test() method, you can do something like

#include <iostream>

using HashStruct = std::size_t;

template<typename ... AA>
using HashFunction = HashStruct & (*)(AA ... );

HashStruct &  hf1 (std::size_t s)
 { static HashStruct val {0U}; return val = s; }

HashStruct &  hf2 (std::size_t s, int i)
 { static HashStruct val {0U}; return val = s + std::size_t(i); }

template <typename Tf, Tf F>
class Collection;

template <typename K, typename ... I, HashFunction<K, I...> F>
class Collection<HashFunction<K, I...>, F>
 {
   public: 

      template <std::size_t N = sizeof...(I)>
      typename std::enable_if<N == 0U, void>::type test ()
       {
         K k=K();

         HashStruct & hh = F(k);

         std::cout << "case 0 (" << hh << ")" << std::endl;
       }

      template <std::size_t N = sizeof...(I)>
      typename std::enable_if<N == 1U, void>::type test ()
       {
         K k=K();

         HashStruct & hh = F(k, 100);

         std::cout << "case 1 (" << hh << ")" << std::endl;
       }
 };

int main ()
 {
   Collection<HashFunction<std::size_t>, hf1>       c1;
   Collection<HashFunction<std::size_t, int>, hf2>  c2;

   c1.test(); // print "case 0 (0)"
   c2.test(); // print "case 1 (100)"
 }

But, if you can pass the extra argument to test(), you don't need SFINAE, you can create a single test() method and all is simpler

#include <iostream>

using HashStruct = std::size_t;

template<typename ... AA>
using HashFunction = HashStruct & (*)(AA ... );

HashStruct &  hf1 (std::size_t s)
 { static HashStruct val {0U}; return val = s; }

HashStruct &  hf2 (std::size_t s, int i)
 { static HashStruct val {0U}; return val = s + std::size_t(i); }

template <typename Tf, Tf F>
class Collection;

template <typename K, typename ... I, HashFunction<K, I...> F>
class Collection<HashFunction<K, I...>, F>
 {
   public: 
      void test (I ... i)
       {
         K k=K();

         HashStruct & hh = F(k, i...);

         std::cout << hh << std::endl;
       }
 };

int main ()
 {
   Collection<HashFunction<std::size_t>, hf1>       c1;
   Collection<HashFunction<std::size_t, int>, hf2>  c2;

   c1.test();    // print "0"
   c2.test(100); // print "100"
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!