c++ - 在这种情况下,c++标准是否保证模板实例化?

标签 c++ templates language-lawyer

template< typename _Type >
struct TypeChecker {};

template< typename _Type >
bool f0( _Type obj )
{
    return TypeChecker< _Type >::value;
}

struct S {};

void f1()
{
    f0( S{} );
}

template<>
struct TypeChecker< S > : std::true_type {};

显然,在定义f1()时“TypeChecker :std::true_type”是未知的,但是MSVC2019和Clang都可以毫无错误地进行编译。

我不确定这是否是标准保证的行为。

我在SO中发现了一些类似的问题:
When is a C++ template instantiation type checked?
Incomplete class usage in template
Can the point-of-instantiation be delayed until the end of the translation unit?

我相信这是规范中的相关部分:

A specialization for a function template, a member function template, or of a member function or static data member of a class template may have multiple points of instantiations within a translation unit, and in addition to the points of instantiation described above, for any such specialization that has a point of instantiation within the translation unit, the end of the translation unit is also considered a point of instantiation.



但是,“翻译单元的末尾也被视为实例化点”到底是什么意思呢?
这是否意味着它依赖于实现?就像“编译器A”编译上面的代码时没有错误,而“编译器B”没有编译一样,而两者均符合标准?

还是可以保证任何标准c++编译器都能正确编写此代码?

最佳答案

您的程序是ill-formed, no diagnostic required,因为显式专门化没有在(或将被)隐式实例化的(第一个)位置之前定义。实例化业务的重点是红色的鲱鱼:它控制名称查找,而不是有效性(除非它也是格式错误的NDR,其查找结果取决于选择了多个实例化点中的哪一个)。

关于c++ - 在这种情况下,c++标准是否保证模板实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60576309/

相关文章:

c++ - 扩展类并保持二进制向后兼容性

c++ - 如何检查哪个#define 被编译成二进制文件?

c++ - 自定义链表使用具有链表的结构创建 RtlValidateHeap 错误

c++ - 散列模板类型

c++ - C4100 "Unreferenced Formal Parameter"在模板中使用时

c++ - 有没有办法为符合标准的 vector 实现插入方法?

c++ - 是否可以编写符合标准的随机访问(或至少向前)整数迭代器?

c++ - C++11 中无法识别的命令行

c++ - C++ 中带有模板的装饰器模式

c++ - C++ 中 for 循环迭代语句期间范围内的变量