使用decltype选择功能专业化

时间:2019-05-11 18:38:47

标签: c++ templates

我想知道为什么在我的示例中我不能使用set supportList to choose from list {"A", "B"} with prompt "Source:" default items {"A"} if supportList is false then return if supportList is {"A"} then set responseList to {"1", "2", "3", "4"} else set responseList to {"5", "6", "7", "8", "9", "10"} end if set misrouteList to choose from list responseList with title "Prepared Responses" with prompt "Reason:" if misrouteList is false then return set supportChoice to item 1 of supportList set prChoice to item 1 of misrouteList 说明符来选择特殊的模板方法。

仅当我使用声明的模板参数来指向专业化时,代码才能按预期工作:

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类型。

1 个答案:

答案 0 :(得分:2)

decltype(first)将产生std::string const &,而函数专门用于Tstd::string的情况。可以通过添加简历限定符和参考来解决此问题:

return sum<::std::remove_const_t<::std::remove_reference_t<decltype(first)>>>(first) + sumBytes(tail...);