vendredi 6 septembre 2019

Deducing parameters from initializer list

So here is the scenario I have been to trying to work upon

#include <iostream>
#include <vector>
#include <string>
#include <complex>

class Double
{
  private:
  double dd;
  std::vector<double> gg;

  std::string ss;

  public:
     Double(double d,const std::string& s = std::string())
     {
         dd = d;
         ss = s;
         gg = std::vector<double>();
     }

     Double(const std::vector<double>& d,const std::string& s = std::string())
     {
         dd = 0;
         ss = s;
         gg = d;
     }

     double getdd() const { return dd; }
};

template<typename T>
Double getDouble(T t,const std::string& s = std::string())
{
    return Double(t,s);
}

std::string to_string(Double d)
{
     double zd = d.getdd() + 1.0;
    return std::to_string(zd);
}

 class TEST 
 {
    public:
    template<typename T_0>
    TEST(const T_0 & var_0)
    {
        auto x = to_string(getDouble(var_0));
    }
};


int main()
{
    TEST ds ({3.4,"ssd"});

    std::cout << "Reached heare\n";
    return 0;
}

Essentially if I call

Double dd ({3.4,"ssd"});

everything works fine but if I try the same thing with the class TEST, I get the following error.

main.cpp: In function 'int main()':
main.cpp:57:25: error: no matching function for call to 'TEST::TEST(<brace-enclosed initializer list>)'
     TEST ds ({3.4,"ssd"});
                         ^
main.cpp:48:5: note: candidate: template<class T_0> TEST::TEST(const T_0&)
     TEST(const T_0 & var_0)
     ^
main.cpp:48:5: note:   template argument deduction/substitution failed:
main.cpp:57:25: note:   couldn't deduce template parameter 'T_0'
     TEST ds ({3.4,"ssd"});
                         ^
main.cpp:44:8: note: candidate: constexpr TEST::TEST(const TEST&)
  class TEST 
        ^
main.cpp:44:8: note:   no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'const TEST&'
main.cpp:44:8: note: candidate: constexpr TEST::TEST(TEST&&)
main.cpp:44:8: note:   no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'TEST&&'

I have tried to deduce the parameters adding a constructor as below

Double (std::initializer_list<boost::any> xx)

but it hasnt worked for me.

Is there any way to get past this issue ? I cant use the explicit type at the callsite since the elements of the initializer list are not of the same type.

Aucun commentaire:

Enregistrer un commentaire