c++ - 显式特化语法

标签 c++

是吗

template <typename T>
void foo(T) {}

template <>
void foo(int) {}

显式特化或函数重载,以及对于显式初始化编译器想看下面的代码吗?

template <typename T>
void foo(T) {}

template <>
void foo<int>(int) {}

我认为该标准接受这两种:

ISO/IEC 14882:2011

14.7.3 Explicit specialization [temp.expl.spec]

1 ...

can be declared by a declaration introduced by template<>; that is:
explicit-specialization:
template < > declaration

最佳答案

两者皆可。在特化

template <>
void foo(int) {}

编译器从函数参数中推断出模板参数T = int。从 14.7.3p10 开始:

A trailing template-argument can be left unspecified in the template-id naming an explicit function template specialization provided it can be deduced from the function argument type.

给出的示例涉及类模板的推导,但它同样适用于直接使用的类型的推导:

template<class T> class Array { /∗ ... ∗/ };
template<class T> void sort(Array<T>& v);
// explicit specialization for sort(Array<int>&)
// with deduced template-argument of type int
template<> void sort(Array<int>&);

关于c++ - 显式特化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13535223/

相关文章:

c++ - std::function 而不是谓词模板

c++ - 如何防止QPushButton调用信号两次?

c++ - 使用 INTEL TBB 的可扩展内存分配

C++ Boost::serialization:如何在一个程序中归档一个对象并在另一个程序中恢复它?

c++ - Libtorrent 库

c++ - 无法将参数 1 从 'std::_Vector_iterator<_Myvec>' 转换为 'std::_Vector_iterator<_Myvec>'

c++ - 与 `list(FILTER)`一起使用时出现REGEX错误

C++:使用整数 move 语义

c++ - 如何链接使用 MSVC 和 AddressSanitizer 编译的程序

c++ - 录制成WAV文件