0

In the following code:

http://coliru.stacked-crooked.com/a/c3ed46591fe7d3af

struct Thingy
{  
  template<class T1>
  void operator=(std::pair<int, T1> p){

  }  
};    

int main()
{
  Thingy thing;
  thing={1, "asd"};
  /*
       This works fine:
       std::pair<int, int> p(1, "asd");
       thing=p;
  */
    return 0;
}

I have this error:

couldn't deduce template parameter 'T1'

It seems that list initialization (curly braces) prevents type deduction. But why?

tower120
  • 5,007
  • 6
  • 40
  • 88
  • 1
    `{1, "asd"}` is not a `pair`, and to deduce to a pair, compile would have to check each type to see it would be a valid pair (as `std::pair`and `std::pair` and `std::pair`)... – Jarod42 Jan 17 '17 at 19:36
  • 1
    *"This works fine: std::pair p(1, "asd");"* I don't think so. `"asd"` to `int`... – Jarod42 Jan 17 '17 at 19:37

1 Answers1

0

I think the problem here is templated overload resolution and implicit conversions (see this question)

I can't quite match the exact usage, but the following works:

template<typename T1>
struct Thingy
{  
  void operator=(const std::pair<int, T1>& p) {
    std::cout << "operator=" << std::endl;
  }  

  void set(std::pair<int, T1> p){
    std::cout << "set" << std::endl;    
  }  
};    

int main()
{
  Thingy<std::string> thing;
  thing = {1, "asd"};
  thing.set({1, "asd"});    // same here
  /*
       This works fine:
       std::pair<int, int> p(1, "asd");
       thing=p;
  */
    return 0;
}

live demo

Biggy Smith
  • 910
  • 7
  • 14