【发布时间】:2014-04-28 18:48:59
【问题描述】:
例如,当我们有一个通用的函数模板时,我们可以在函数中使用模板类型:
template <typename T>
void foo()
{
T t;
...
}
现在,想象一下这个函数模板的特化:
template <>
void foo<MySpecialType>()
{
T t; // Does not compile, no knowledge of formal template argument T
MySpecialType t2; // This is OK, but I have to mention MySpecialType again
}
template <>
void foo<MySpecialType2>()
{
T t; // Does not compile, no knowledge of formal template argument T
MySpecialType2 t2; // This is OK, but I have to mention MySpecialType2 again
}
请注意,在上述两种特化中,我必须提到在函数体内按名称特化的模板参数的类型。我宁愿使用更通用的占位符(即 T),而不是在函数模板特化的主体中重复(可能多次)被特化的类型。
如果有一种方法可以在实际的专业化函数定义处使用 T 或创建别名,那就太好了。我知道我可以通过实际函数体内的类型别名来做到这一点:
template<>
void foo<MySpecialType>
{
using T=MySpecialType; // But then I still repeat the type at least once
...
我更喜欢这样的专业化约定:
// Warning: Not valid C++
template<>
void foo<T=MySpecialType>
{
T t;
...
或者:
// Warning: Not valid C++
template<T>
void foo<MySpecialType>
{
T t;
...
感谢您的建议。
【问题讨论】:
-
T在这种情况下会是什么? -
我很好奇你为什么关心这个。我并不是要轻率——我怀疑我知道为什么,这可能会影响如何最好地解决这个问题。
-
你是说让复制粘贴代码编写更容易吗?
-
@John,我指的是每个专业都按名称提及一个类型。由于每个专业化都针对不同的类型,因此必须至少提及其类型一次。我想看看这个“至少一次”是否也可以变成“最多一次”,以避免通过名称提及多余的类型。
-
此外,您似乎正在将非专业化的实现视为您在专业化中尝试实现的标准。但是你必须在那里“提及”
T至少两次。