template pass by value or const reference or…?

后端 未结 5 2011
既然无缘
既然无缘 2020-12-09 20:31

I can write a templated function this way

template void f(T x) {…}

or this way

template void f(T         


        
5条回答
  •  醉梦人生
    2020-12-09 21:12

    Thou shalt not wake the dead, but head a similar problem and here's some example code that shows how to use C++11s type traits to deduce whether a parameter should be passed by value or reference:

    #include 
    #include 
    
    template
    class example
    {
        using parameter_type = typename std::conditional::value, key_type, key_type&>::type;
    
     public:
      void function(parameter_type param)
      {
          if (std::is_reference::value)
          {
              std::cout << "passed by reference" << std::endl;
          } else {
              std::cout << "passed by value" << std::endl;
          }
      }
    };
    
    struct non_fundamental_type
    {
        int one;
        char * two;
    };
    
    int main()
    {
      int one = 1;
      non_fundamental_type nft;
    
      example().function(one);
      example().function(nft);
    
      return 0;
    }
    

    Hope it helps others with a similar issue.

提交回复
热议问题