【问题标题】:template overload not found未找到模板重载
【发布时间】:2018-08-23 09:50:18
【问题描述】:

我试图理解为什么在下面的代码中断言失败。

// file dconvert.h
struct A{};
struct B{int n;};
struct C{double cc;};

template<class FromStruct, class ToStruct>
void dconvert(FromStruct from, ToStruct to)
  {
  struct Placeholder {FromStruct f;};
  static_assert(std::is_same<Placeholder, FromStruct>::value, "CONVERSION NOT DEFINED");
  }

template<class FromStruct>
void dconvert(FromStruct from,
              int to)
  {

  }

template<class FromStruct>
void dconvert(FromStruct from,
              C to)
  {

  dconvert<FromStruct,int>(from, 5);

  }


// file main.cpp
#include <dconvert.h>
int main()
{
  ::dconvert(3,1); // ok
  C c;
  ::dconvert(3,c); // static assertion fails!
}

如果没有实现其他显式转换函数,则认为主 dconvert 函数断言。

我不明白为什么没有看到 dconvert 函数重载。

如果我删除这些行:

C c;    
::dconvert(3,c);

或者如果我保留上述内容并删除

dconvert<FromStruct,int>(from, 5);

不抛出任何断言

【问题讨论】:

  • 你只有overloads,没有specializations
  • 感谢您的建议,我更喜欢使用消息,所以我会坚持断言。我喜欢 static_assert(false, "")
  • static_assert(false, "") 使程序格式错误,但static_assert(always_false&lt;FromStruct&gt;::value, "") 很好。与(全局范围)template &lt;typename T&gt; struct always_false : std::false_type {};.
  • 没错。如果我只留下 false 似乎会有问题

标签: c++ templates compiler-errors overloading template-specialization


【解决方案1】:

这是因为在:

template<class FromStruct>
void dconvert(FromStruct from,
              C to)

你这样做:

dconvert<FromStruct,int>(from, 5);

因此明确要求实例化第一个模板(因为它是唯一具有两个模板参数的模板)方法。如果您要删除此需求,例如通过离开它允许模板类型推断发生:

dconvert(from, 5);

代码可以毫无问题地编译。 在clang6.0上测试。

【讨论】:

  • 所以你是说每次我不使用演绎,第一个模板,带有断言的模板总是被实例化。这对我来说仍然没有多大意义
  • 您明确要求使用具有两个类型参数的模板。因此,唯一的一个配件是带有 static_static 断言的那个。您也可以调用 dconvert(from, 5) 并对其进行编译。但是,只要您要求一个具有两个模板参数的模板方法,就只有一个适合。
猜你喜欢
  • 2015-01-03
  • 2015-09-04
  • 2011-03-01
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
相关资源
最近更新 更多