使用声明类型选择函数专业化
Using decltype to choose function specialization
我想知道为什么在我的示例中我不能使用 decltype
指示符选择专门的模板方法。
只有当我使用声明的模板参数来点专业化时,代码才能按预期工作:
template <typename T>
auto sum(const T& value)
{
std::cout << "sum for template" << std::endl;
return sizeof(value);
}
template<>
auto sum(std::string const& value)
{
std::cout << "sum for string" << std::endl;
return value.length();
}
template <typename Last>
auto sumBytes(const Last& last)
{
return sum<Last>(last);
}
template <typename First, typename ...Tail>
auto sumBytes(const First& first, const Tail& ...tail)
{
return sum<First>(first) + sumBytes(tail...);
}
int main()
{
std::string str = "hello";
auto sum = sumBytes(str,2,3,4);
}
正如预期的那样,字符串函数的专业化被称为字符串参数。
但是,当我使用 decltype
确定第一个参数的类型时,未调用字符串的专用函数,正在选择通用的功能:
template <typename T>
auto sum(const T& value)
{
std::cout << "sum for template" << std::endl;
return sizeof(value);
}
template<>
auto sum(std::string const& value)
{
std::cout << "sum for string" << std::endl;
return value.length();
}
template <typename Last>
auto sumBytes(const Last& last)
{
return sum<decltype(last)>(last);
}
template <typename First, typename ...Tail>
auto sumBytes(const First& first, const Tail& ...tail)
{
return sum<decltype(first)>(first) + sumBytes(tail...);
}
int main()
{
std::string str = "hello";
auto sum = sumBytes(str,2,3,4);
}
我想知道为什么在使用decltype
指示符时,未调用字符串的专业化?据我所知,decltype
应返回const std::string&
类型。
decltype(first)
将产生 std::string const &
,而当T
为 std::string
时,功能专门为情况。这可以通过Doropping CV预选赛和参考来解决:
return sum<::std::remove_const_t<::std::remove_reference_t<decltype(first)>>>(first) + sumBytes(tail...);
相关文章:
- 函数模板部分专业化-有什么解决方法吗
- 我应该声明我的函数模板专业化还是定义它们就足够了
- std::转换move构造函数的模板专业化的变体
- 常量函数参数的专业化
- 纯虚函数的模板专业化
- 删除模板函数,除了它的一个专业化
- 为什么这不是函数模板的部分专业化
- 在允许的函数模板的明确专业化中扣除了多个模板参数
- 使用声明类型选择函数专业化
- 关于函数的完整专业化的名称查找的漫画
- C - 具有非类型模板参数的模板类上的专业化函数模板
- C++11性能:Lambda内联与函数模板专业化
- 为什么不允许对成员函数的模板专业化
- 成员函数模板参数的部分专业化
- C 将lambda函数用作模板功能专业化
- 对于需要其他模板参数的类型函数的部分模板专业化
- 特定成员函数的部分专业化
- 指针作为函数返回类型的部分专业化
- 为什么未经声明未从.cpp文件拾取模板函数的完整专业化
- 模板成员函数专业化