C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 如何编写接受\u0026\u0026和const&both的模板函数?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
例如

template<typename T> void f(T&& t) {}
template<typename T> void f(T const& t) {}

我打电话的时候

int i;
f(i); // call f(T&&) which I expect to call f(T const&),how to solve it?
f(10); // call f(T&&),that is fine

解决方法

这是一种方式:

#include <type_Traits>

template<typename T>
typename std::enable_if< !std::is_lvalue_reference<T>::value >::type
f(T&& t) {}

template<typename T> void f(T const& t) {}

标签调度的另一种可能性是:

template<typename T>
void f_(const T&,std::true_typE) { std::cout << "const T&\n"; }
template<typename T>
void f_(T&&,std::false_typE) { std::cout << "T&&\n"; }

template<typename T>
void f(T&& t)
{
    f_(std::forWARD<T>(t),std::is_lvalue_reference<T>{} );
}

大佬总结

以上是大佬教程为你收集整理的c – 如何编写接受\u0026\u0026和const&both的模板函数?全部内容,希望文章能够帮你解决c – 如何编写接受\u0026\u0026和const&both的模板函数?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。