假设我有两个模板用于重载
operator=
:class MyClass {
public:
template <typename T>
std::enable_if_t<true == /* a condition */, MyClass&>
operator=(T value) {
std::cout << "Pass by copy" << std::endl;
}
template <typename T>
std::enable_if_t<false == /* a condition */, MyClass&>
operator=(const T &value) {
std::cout << "Pass by reference" << std::endl;
}
};
std::enable_if
最优的使用条件是什么?
我想到了这个:
template <typename T>
struct pass_copy_cond : std::conditional<
std::is_fundamental<T>::value ||
std::is_pointer<T>::value ||
(std::is_trivial<T>::value && sizeof(T) < sizeof(void*))
, std::true_type, std::false_type>::type {};
有没有办法改善情况?
std::conditional_t
来确定参数类型,而不是使用enable_if
。优点在于您只需编写一次函数,避免重复劳动。 - François Andrieuxoperator()
完美地转发到一个实际实现行为的私有函数,但此时我不确定它是否仍然值得这样做。 - François Andrieux