如果我正在编写一个将参数转发给构造函数的通用函数,有没有办法判断它是否是复制构造函数?本质上我想做的是:
template <typename T, typename... Args>
void CreateTAndDoSomething(Args&&... args) {
// Special case: if this is copy construction, do something different.
if constexpr (...) { ... }
// Otherwise do something else.
...
}
我想出的最好的方法是检查sizeof...(args) == 1
然后看着std::is_same_v<Args..., const T&> || std::is_same_v<Args..., T&>
。但我认为这错过了一些边缘情况,例如易失性限定输入和隐式转换为的东西T
.
老实说,我不完全确定这个问题是明确定义的,所以请随意告诉我它不是(以及为什么)。如果有帮助,您可以假设唯一的单参数构造函数T
are T(const T&)
and T(T&&)
.
如果我是对的,因为复制构造函数不是一个东西,所以这没有明确定义,那么也许可以通过说“我如何判断表达式是否T(std::forward<Args>(args)...)
选择一个接受的重载const T&
?
您可以使用remove_cv_t:
#include <type_traits>
template <typename T, typename... Args>
void CreateTAndDoSomething(Args&&... args) {
// Special case: if this is copy construction, do something different.
if constexpr (sizeof...(Args) == 1 && is_same_v<T&, remove_cv_t<Args...> >) { ... }
// Otherwise do something else.
...
}
这涵盖了所有“复制构造函数”defined https://eel.is/c++draft/class.copy.ctor#1按照标准,不考虑可能的默认参数(很难确定给定的函数参数(对于给定这些参数将调用的函数)是否是默认的)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)