这是来自 ISO C++ 标准 14.6/7 的声明:
Knowing which names are type names allows the syntax of every template
definition to be checked. No diagnostic shall be issued for a template definition for which a valid specialization can be generated. If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required. If a type used in a non-dependent name is incomplete at the point at which a template is defined but is complete at the point
at which an instantiation is done, and if the completeness of that type
affects whether or not the program is well-formed or affects the semantics
of the program, the program is ill-formed; no diagnostic is required. [Note: if a template is instantiated,errors will be diagnosed according to the other rules in this Standard. Exactly when these errors are diagnosed is a quality of implementation issue. ]
例子:
int j;
template<class T> class X {
// ...
void f(T t, int i, char* p)
{
// diagnosed if X::f is instantiated
t = i;
// and the assignment to t is an error
// may be diagnosed even if X::f is
p = i;
// not instantiated
// may be diagnosed even if X::f is
p = j;
// not instantiated
}
void g(T t) {
// may be diagnosed even if X::g is
+;
// not instantiated
}
};
(多为失败案例) 任何人都可以为这个陈述说更多的例子..像这样..好吗?
最佳答案
void f<T>() "I am an ill-formed 'template definition' parameterized on T.";
一个实现被允许接受上面的语法格式错误的模板定义,并且在它被实际实例化之前不对其进行诊断。希望这可以解释。 (当然我在开玩笑,但我并不是完全不认真。它显示了上面引用文本的一个缺陷:没有可以包含“;+;”的“模板定义”)。
关于不完整类型的另一件事是以下内容格式错误但不需要诊断
struct foo;
template<typename T>
void f() { foo x; }
// foo is incomplete here
struct foo { };
// foo is complete here
int main() { f<int>(); }
标准中的“不需要诊断”规则允许实现以它认为合适的方式运行(这使得任何违反不需要诊断的规则的程序都具有有效的未定义行为)。因此,您引用的文字确实是(恕我直言)法律不当。
参见 Confused about ill-formed templates和 Compiling C++ templates as opposed to preprocessing them (以 Digital Mars 名声大噪 Walter Bright )
关于c++ - 模板 :Name resolution -->can any one tell some more examples for this statement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3734632/