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/