我试图理解为什么在以下代码中断言失败。
// 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);
没有断言被抛出
最佳答案
这是因为在:
template<class FromStruct>
void dconvert(FromStruct from,
C to)
你这样做:
dconvert<FromStruct,int>(from, 5);
因此明确要求实例化第一个模板(因为它是唯一具有两个模板参数的模板)方法。如果您要删除此需求,例如通过保留它来允许模板类型推导发生:
dconvert(from, 5);
代码可以毫无问题地编译。 在 clang6.0 上测试。
关于c++ - 未找到模板重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51982950/