我想检查一个模板类型并适当地调用一个函数。但是,这似乎并不奏效。我尝试了is_same,C++ compile-time type checking,compile-time function for checking type equality和boost :: is_same。一切都给了我同样的错误。以下是示例代码。编译时检查模板类型C++
#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
在这种情况下,我既没有字符串也没有数字类。它来自第三方库。我只实现MyClass,它将被打包为另一个库。我期望使用MyClass的应用程序将传递给我一个属于第三方类的String或Numeric。 MyClass是一种专门的矩阵操作,密集/稀疏矩阵是来自第三方库的数字和字符串类。我想检查使用我的库和第三方库的应用程序是否正在根据属于第三方库的类类型调用MyClass。
请让我知道如何解决这个问题。
我既没有字符串或数字类。它来自第三方库。我只实现MyClass,它将被打包为另一个库。使用MyClass的应用程序将传递给我一个属于第三方类的String或Numeric。例如,String和Numeric类是来自第三方库的密集和稀疏矩阵。我想检查使用我的库和第三方库的应用程序是否正在根据属于第三方库的类类型调用MyClass。 –
@RamakrishnanKannan:这个答案只改变了'Myclass' –
只是要清楚,这可以使用SFINAE。关键是编译器有两个版本的'checkNumeric',如果其中一个产生了错误,那么它将被默认地从考虑中删除。 – Adam