【发布时间】:2014-06-19 09:32:07
【问题描述】:
C++03 中禁止局部类型作为模板参数:
template<typename T>
struct Foo { };
void Make()
{
struct Unknown {};
Foo<Unknown> foo; // Bad
}
标准中是否有关于在模板未实例化的情况下检查此规则的指令?
是否可以确定,仅在模板实例化尝试后才检查此规则(没有实例化 => 编译成功)?
template<typename T>
struct Foo { };
template<typename T>
void Do(T&) { }
template<typename T>
void Do(T*) // usage with pointer is forbidden by-design
{
struct Unknown {};
Foo<Unknown>::UnknownMethod();
}
int main()
{
std::string s;
Do(s);
}
【问题讨论】:
-
可能是
std::static_assert()可以帮助这样做。 -
它在 C++ 2003 中不存在
-
这里有一些代码,如何用旧的 c++ 版本自己实现:github.com/makulik/StaticInterfaces
-
@πάνταῥεῖ
static_assert怎么能帮到你? -
@Constructor:正如我在回答中解释的那样,
static_assert可以在这里提供帮助。因为这是“我如何使用 X 来做 Y”形式的典型问题,其中答案不可避免地是“使用 Z 代替”。幸运的是提到了“Y”,所以我们可以说静态断言是寻找的“Z”。
标签: c++ templates instantiation c++03 local-class