编译时检查模板类型C.

编译时检查模板类型C.,第1张

概述我正在尝试检查模板类型并适当调用一个函数.但是,这似乎不起作用.我尝试使用is_same, C++ compile-time type checking, compile-time function for checking type equality和boost :: is_same.一切都给了我同样的错误.以下是示例代码. #include <iostream>#include <type_ 我正在尝试检查模板类型并适当调用一个函数.但是,这似乎不起作用.我尝试使用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 @R_502_6852@: ../src/TestCPP.cppInvoking: GCC C++ Compilerg++ -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 = Numerictemplate<> voID Myclass<Numeric>::checkNumeric() {    cout << "is numeric = " << temp.isNumeric() << endl;}
总结

以上是内存溢出为你收集整理的编译时检查模板类型C.全部内容,希望文章能够帮你解决编译时检查模板类型C.所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1222002.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存