c++ - C++ 模板只是 "grammar safe"并且首先不是类型安全的?

标签 c++ templates types language-lawyer

C++ 模板至少检查两次。首先是声明和定义模板时,其次是实例化模板时。模板成功实例化后,它处于类型安全状态。我的问题是,成功声明和定义模板时,模板所处状态的名称是什么? 如果我将宏与模板进行比较,在成功的宏“实例化”之后代码是否是类型安全的?

#define BAR(x) return x;
                        ^
// BAR is preprocessor-grammar-safe here?

struct Bar
{
  static void bar() {}
};
  ^
// Bar is type safe at this point?

template<typename T>
void foo()
{
  T::bar();
}
 ^
// foo is C++-grammar safe at this point?

int main()
{
  foo<Bar>();
             ^
  // foo is type safe at this point?

  foo<int>();
         ^
  // foo is ill-formed here?

  BAR(0);
         ^
  // BAR is type safe at this point?

  return 0;
}

最佳答案

将 C++ 模板视为类固醇和具有句法知识的宏。 例如。

template<typename T> 
void func(T t) {
  t.foo();
  ...

没有声明 T 必须具有 foo() 函数这一事实; 这将 C++ 模板与 Scala 类型参数之类的东西区分开来。 我相信较新的 C++ 版本为此添加了一些支持。您基本上让编译“尝试”使用 t.foo(),如果没有这样的函数,它就无法编译。

关于c++ - C++ 模板只是 "grammar safe"并且首先不是类型安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20642475/

相关文章:

c++ - 我的循环不会循环

types - FSharp 根据谓词定义类型

postgresql - 如何自动将空格填充到预定长度的列?

c++ - 什么时候应该使用模板而不是继承,反之亦然?

c# - 表单设计器打破了通用抽象 UserControl

postgresql - 如何减少 PostgreSQL 数据库的大小?

c++ - 如何覆盖 opencv Mat 的子图像?

c++ - 将 shared_ptr<Type> 转换为 weak_ptr<void> 并返回

C++ 静态多数组包装器

C++如何识别无符号类型?