元组/对模板推导失败,列表初始化

时间:2017-01-17 19:13:28

标签: c++ templates

在以下代码中:

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;
}

我有这个错误:

couldn't deduce template parameter 'T1'

列表初始化(花括号)似乎可以防止类型扣除。但为什么呢?

1 个答案:

答案 0 :(得分:0)

我认为这里的问题是模板化的重载决策和隐式转换(see this question

我无法完全匹配确切用法,但以下工作:

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