取决于类型C的不同值
发布时间:2020-12-16 09:59:37 所属栏目:百科 来源:网络整理
导读:我想根据输入变量的类型有不同的变量值. 码: template typename Tint getValue(vectorT data){ return something; // There should be 0 for int and 1 for double} 有谁知道如何实现这样的功能? 解决方法 如果您只是处理int和double,那么您可以为不同类型
我想根据输入变量的类型有不同的变量值.
码: template <typename T> int getValue(vector<T> & data) { return something; // There should be 0 for int and 1 for double } 有谁知道如何实现这样的功能? 解决方法
如果您只是处理int和double,那么您可以为不同类型的向量重载函数.
int getValue(vector<int> & data) { return 0; } int getValue(vector<double> & data) { return 1; } 如果你想将getValue作为模板函数并专门用于int和double,那么你可以使用 template<typename T> int getValue(std::vector<T> & data) { return -1; } template <> int getValue(std::vector<int> & data) { return 0; } template <> int getValue(std::vector<double> & data) { return 1; } Live Example (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |