Rau*_*nso 3 c++ sfinae template-meta-programming c++11
我在C++中有以下代码:
struct A;
struct B
{
B(){}
template<typename T>
B(T param){}
};
Run Code Online (Sandbox Code Playgroud)
我希望构造函数模板仅在typename T可转换为类型时才有效A.完成此任务的最佳方法是什么?
Rei*_*ica 10
你想启用构造函数,如果 T 可以转换为A?使用std::enable_if和std::is_convertible:
template <
class T,
class Sfinae = typename std::enable_if<std::is_convertible<T, A>::value>::type
>
B(T param) {}
Run Code Online (Sandbox Code Playgroud)
这适用于申请SFINAE ; 如果T不能转换为A,则替换将失败,构造函数将从候选重载集中删除.