Home > Net >  how to make an unnecessary long code compact using template
how to make an unnecessary long code compact using template

Time:10-08

#include <iostream>
#include <vector>
#include <string>
#include <tuple>
#include <utility>
using namespace std;



   
class defaultValues
   {
   public:
      static std::tuple<bool,int,unsigned int, size_t, double, float, std::string,
      std::wstring > tup;

 
      static decltype(std::get<0>(tup))& getDefault(bool ) { return std::get<0>(tup); }
      static decltype(std::get<1>(tup))& getDefault(int ) { return std::get<1>(tup); }
      static decltype(std::get<2>(tup))& getDefault(decltype(std::get<2>(tup) )) { return std::get<2>(tup); }
      static decltype(std::get<3>(tup))& getDefault(decltype(std::get<3>(tup))) { return std::get<3>(tup); }
      static decltype(std::get<4>(tup))& getDefault(double ) { return std::get<4>(tup); }
      static decltype(std::get<5>(tup))& getDefault(decltype(std::get<5>(tup)) ) { return std::get<5>(tup); }
      static decltype(std::get<6>(tup))& getDefault(decltype(std::get<6>(tup)) &) { return std::get<6>(tup); }
      static decltype(std::get<7>(tup))& getDefault(decltype(std::get<7>(tup)) &) { return std::get<7>(tup); }
  
   };

std::tuple<bool,int,unsigned int, size_t, double, float, std::string,
      std::wstring> defaultValues::tup = std::make_tuple(false,int(0),0,size_t(0), double(0.0),float(0.0),std::string(""),std::wstring(L""));


int main() {
    std::cout<<defaultValues::getDefault(false)<<std::endl;
    // your code goes here
    return 0;
}

Now I have some questions,

  1. I feel the code should be compressible using templates. I tried something like
    template<int N> 
    static decltype(std::get<N>(tup))& getDefault(bool ) { return std::get<N>(tup); }

to replace the functions but it did not work.

  1. Why can't I use decltype<std::get<0>> instead of bool in the first function. When I do that I get some ambiguity and the compiler complains.

I would appreciate all input I can get.

CodePudding user response:

As long as you do not have duplicate types in your tuple, you can use the type version of get to reduce the code to

class defaultValues
{
public:
  static std::tuple<bool,int,unsigned int, size_t, double, float, std::string,
  std::wstring > tup;

  template <typename T>
  static auto& getDefault(T) { return std::get<T>(tup); }

};
  • Related