【发布时间】: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<FromStruct>::value, "")很好。与(全局范围)template <typename T> struct always_false : std::false_type {};. -
没错。如果我只留下 false 似乎会有问题
标签: c++ templates compiler-errors overloading template-specialization