【发布时间】:2016-09-02 10:26:41
【问题描述】:
对于模板函数,我们可以将其特化如下:
template <typename T>
void func(T t) {}
// specialization for int
template <>
void func(int t) {}
但是,我不确定如何使用通用引用(来自Meyers' book 的名称)专门化模板函数。
// template function with universal reference
template <typename T>
void func(T &&t) {}
我认为简单地将T 替换为int 并不能使其成为专业化:
template <>
void func(int &&t) {}
由于模板函数可以接受左值和右值,而“特化”函数只能接受右值。
我还应该用左值引用定义一个“专业化”吗?
// 'specialization' for lvalue reference
template <>
void func(int &t) {}
而这两个“特化”使原始模板函数的特化?或者有专门的专业有什么意义吗?
【问题讨论】:
-
你是说你想为一个 int 参数的所有表达式专门化 func,即 int、int&、int&&、const int& ?
-
你能不能再高一点,在更高的层次上描述你想要解决的问题?
-
对这些特定示例进行专门化并没有多大意义,而不仅仅是完全的重载。
-
@RichardHodges 我想将它专门用于
int&和int&&。为了您的提醒,也许还有const int&。我认为int是不考虑的,因为在功能void func(T &&t),t永远不能到int