c++模板专门化语法
C++ templates specialization syntax
在c++ Primer Plus(2001,捷克语翻译)中,我发现了这些不同的模板特化语法:
函数模板
template <typename T> void foo(T);
专业化语法
void foo(int param); // 1
void foo<int>(int param); // 2
template <> void foo<int>(int param); // 3
template <> void foo(int param); // 4
template void foo(int param); // 5
在谷歌上搜索了一下,我只找到了第三个例子。它们之间(在调用、编译、用法)有什么区别吗?它们中的一些已经过时了吗?为什么不直接用一号呢? 每种语法的注释如下:
void foo(int param); //not a specialization, it is an overload
void foo<int>(int param); //ill-formed
//this form always works
template <> void foo<int>(int param); //explicit specialization
//same as above, but works only if template argument deduction is possible!
template <> void foo(int param); //explicit specialization
//same as above, but works only if template argument deduction is possible!
template void foo(int param); //explicit instantiation
由我添加:
//Notice <int>. This form always works!
template void foo<int>(int param); //explicit instantiation
//Notice <>. works only if template argument deduction is possible!
template void foo<>(int param); //explicit instantiation
从编码的角度来看,重载优于函数模板专门化。
所以,不要专门化函数模板:
- 为什么不特化函数模板?
- 模板专门化和重载
要了解术语:
- 实例化
- 显式实例化 专业化
- 明确专业化
参见:
- c++模板中实例化和专门化的区别
使用Visual Studio 2012,如果没有函数参数,它的工作似乎略有不同:
template <typename T> T bar( );
//template int bar<int>( ) { return 0; } doesn't work
template < > int bar<int>( ) { return 0; } //does work
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 是否可以对零模板参数进行模板专门化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 单独定义模板化嵌套类方法的正确语法
- 尝试根据类中 typedef 的存在来专门化模板函数
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- c++模板专门化语法
- 显式模板专门化的语法
- 模板专门化GCC的语法错误,但MSVC没有
- c++模板全专门化语法
- 需要语法帮助来专门化基于模板参数类型的类方法
- c++中专门化函数模板的语法
- 模板专门化语法错误?不确定
- 定义模板方法专门化的正确语法是什么?