在C++中,根据模板的类型,只构建代码的一部分是否可能?这将是类似于以下内容:
#include <iostream>
using namespace std;
template<typename T>
void printType(T param)
{
#if T == char*
cout << "char*" << endl;
#elif T == int
cout << "int" << endl;
#else
cout << "???" << endl;
#endif
}
int main()
{
printType("Hello world!");
printType(1);
return 0;
}
std::is_same<T, char*>::value
不会处理字符串字面量,比如"Hello world!"
,因为它们会衰减为const char*
而不是char*
,而在第二个示例中,void printType(char* partam)
也不会接受字符串字面量。因此,你应该考虑在第一个示例中使用std::remove_cv<T>::type
,在第二个示例中使用const char*
。 - undefined