编译时检查模板类型C.
发布时间:2020-12-16 10:41:03 所属栏目:百科 来源:网络整理
导读:我正在尝试检查模板类型并适当调用一个函数.但是,这似乎不起作用.我尝试使用is_same,C++ compile-time type checking,compile-time function for checking type equality和boost :: is_same.一切都给了我同样的错误.以下是示例代码. #include iostream#inclu
我正在尝试检查模板类型并适当调用一个函数.但是,这似乎不起作用.我尝试使用is_same,C++ compile-time type checking,compile-time function for checking type equality和boost :: is_same.一切都给了我同样的错误.以下是示例代码.
#include <iostream> #include <type_traits> using namespace std; class Numeric { public : bool isNumeric() { return true; } }; class String { }; template <class T> class Myclass { private: T temp; public: void checkNumeric() { if(std::is_same<T,Numeric>::value) { cout << "is numeric = " << temp.isNumeric(); } else { cout << "is numeric = false" << endl; } } }; int main() { Myclass<Numeric> a; a.checkNumeric(); Myclass<String> b; b.checkNumeric(); } 在编译上面的代码时,我收到以下错误. make all Building file: ../src/TestCPP.cpp Invoking: GCC C++ Compiler g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/TestCPP.d" -MT"src/TestCPP.d" -o "src/TestCPP.o" "../src/TestCPP.cpp" ../src/TestCPP.cpp:36:36: error: no member named 'isNumeric' in 'String' cout << "is numeric = " << temp.isNumeric(); ~~~~ ^ ../src/TestCPP.cpp:51:4: note: in instantiation of member function 'Myclass<String>::checkNumeric' requested here b.checkNumeric(); ^ 1 error generated. make: *** [src/TestCPP.o] Error 1 在这种情况下,我既没有String或Numeric类.它来自第三方图书馆.我只实现了MyClass,它将被打包为另一个库.我希望使用MyClass的应用程序将传递给属于第三方类的String或Numeric. MyClass是一个专门的矩阵操作,Dense / Sparse矩阵是来自第三方库的类数字和字符串类.我想检查使用我的库和第三方库的应用程序是否根据属于第三方库的类类型调用MyClass. 请告诉我如何解决这个问题. 解决方法
不需要做任何花哨的事情;这可以使用普通的模板专业化来处理.
template <class T> class Myclass { private: T temp; public: // called for general T void checkNumeric() { cout << "is numeric = false" << endl; } }; // specialized version for T = Numeric template<> void Myclass<Numeric>::checkNumeric() { cout << "is numeric = " << temp.isNumeric() << endl; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |