C – 专门化类模板的成员函数
我正在寻找模板的帮助.我需要在模板中创建对特定类型有不同反应的函数.
它可能看起来像这样: template <typename T> class SMTH { void add() {...} // this will be used if specific function isn't implemented void add<int> {...} // and here is specific code for int }; 我也尝试在单个函数中使用typeid和swich through类型,但对我来说不起作用. 解决方法
你真的不希望在运行时使用typeid进行这种分支.
我们想要这个代码: int main() { SMTH<int>().add(); SMTH<char>().add(); return 0; } 要输出: int not int 有很多方法可以实现这一点(所有这些都在编译时,其中一半需要C 11): > Specialize全班(如果它只有这个添加功能): template <typename T> struct SMTH { void add() { std::cout << "not int" << std::endl; } }; template <> struct SMTH<int> { void add() { std::cout << "int" << std::endl; }; }; >仅专注于添加成员功能(由@Angelus推荐): template <typename T> struct SMTH { void add() { std::cout << "not int" << std::endl; } }; template <> // must be an explicit (full) specialization though void SMTH<int>::add() { std::cout << "int" << std::endl; } 请注意,如果使用cv-qualified int实例化SMTH,则将获得上述方法的not int输出. >使用SFINAE成语.它的变体很少(默认模板参数,默认函数参数,函数返回类型),最后一个适合这里: template <typename T> struct SMTH { template <typename U = T> typename std::enable_if<!std::is_same<U,int>::value>::type // return type add() { std::cout << "not int" << std::endl; } template <typename U = T> typename std::enable_if<std::is_same<U,int>::value>::type add() { std::cout << "int" << std::endl; } }; 主要的好处是你可以使启用条件复杂化,例如使用std :: remove_cv选择相同的重载,无论cv-qualifiers如何. template <typename> struct is_int : std::false_type {}; // template specialization again,you can use SFINAE,too! template <> struct is_int<int> : std::true_type {}; template <typename T> struct SMTH { void add() { add_impl(is_int<T>()); } private: void add_impl(std::false_type) { std::cout << "not int" << std::endl; } void add_impl(std::true_type) { std::cout << "int" << std::endl; } }; 这当然可以在不定义自定义标记类的情况下完成,add中的代码如下所示: add_impl(std::is_same<T,int>()); 我不知道我是否全部提到它们,我也不知道为什么我会这样做.您现在要做的就是选择最适合使用的那个. 现在,我明白了,你也想检查一个函数是否存在.这已经很久了,有一个existing QA. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |