成员函数实例化
Member function instantiation
以下内容在GCC 4.8.1上编译(使用--std=c++11
):
struct non_default_constructible { non_default_constructible() = delete; };
template<class T>
struct dummy {
T new_t() { return T(); }
};
int main(int argc, char** argv) {
dummy<non_default_constructible> d;
return 0;
}
棘手的部分是dummy<non_default_constructible>::new_t()
显然格式不正确,但这并不能阻止编译器实例化dummy<non_default_constructible>
。
这是标准规定的行为吗?相关章节/关键词是什么?
类模板的成员函数只有在上下文需要时才会实例化,这意味着在尝试使用new_t()
之前不会看到任何错误。C++标准的相关部分是:
§14.7.1隐式实例化
[temp.inst]
除非函数模板专门化已显式实例化或显式专门化,否则当在需要函数定义存在的上下文中引用该专门化时,函数模板专业化将隐式实例化。除非调用是对函数模板显式专用化或显式专用类模板的成员函数的调用,否则当在需要默认参数值的上下文中调用函数时,函数模板或类模板成员函数的默认参数将被隐式实例化。
示例:
template<class T> struct Z { void f(); void g(); }; void h() { Z<int> a; // instantiation of class Z<int> required Z<char>* p; // instantiation of class Z<char> not required Z<double>* q; // instantiation of class Z<double> not required a.f(); // instantiation of Z<int>::f() required p->g(); // instantiation of class Z<char> required, and // instantiation of Z<char>::g() required }
本例中没有任何内容要求
class Z<double>
、Z<int>::g()
或Z<char>::f()
隐式实例化。--结束示例]
相关文章:
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 模板化类构造函数的模板实例化
- 何时需要实例化函数模板定义?
- clang:使用 O3 导出隐式实例化函数的符号
- 如何调用模板函数的每个实例化函数
- 使用泛型类型显式实例化函数模板
- 使用自动>decltype方法显式实例化函数
- MSVC 编译器实例化函数模板的默认定义,即使存在专用化
- 如何使用模板模板参数显式实例化函数
- 实例化函数模板的编译问题
- Lua到c++,用于实体修改的实例化函数
- 当类型参数为空时,无法实例化函数模板
- 调用实例化函数时发生链接器错误
- 实例化函数的多个模板并在运行时选择的通用解决方案
- 使用不完整类型显式实例化函数模板
- 实例化函数模板时出错
- 禁止使用迭代器形参实例化函数模板