转载:C++模板 按条件匹配(enable_if_t) - 简书 (jianshu.com)
重点:
当一份标准模板函数无法解决特定情况时,按条件匹配进入特定模板函数就变成了不可或缺.
using namespace std;
template<typename T,typename enable_if<is_integral<T>::value,int>::type =0>
void example(T t)
{
cout << t << endl;
}
//enable_if_t 去掉了typename 和::type
template<typename T,enable_if_t<is_integral<T>::value, int> = 0>
void exampleTest(T t)
{
cout << t << endl;
}
int main()
{
example(123);
exampleTest(456);
return 0;
}
禁止拷贝和复制函数转化
using namespace std;
//std::is_convertiable<FROM, TO> 处理类型
template<typename T>
using EnableIfString = enable_if_t<is_convertible_v<T, string>>;
class Person
{
public:
template<typename T,typename =EnableIfString<T>>
explicit Person(T&& n):name(forward<T>(n))
{
cout << "T&&: " << name << endl;
}
Person(const Person& p) :name(p.name)
{
cout << "const Person&: "<<name << endl;
};
Person(Person&& p) :name(move(p.name))
{
cout << "Person&&: " << name << endl;
};
private:
string name;
};
int main()
{
string s = "name";
Person p1(s);
Person p2("test");
Person p3(p1);
Person p4(move(p1));
return 0;
}