我想运行以下代码:
#include <iostream>
#include <type_traits>
template<class ... T, class T1, bool B = std::is_integral<T1>::value>
void printIntegrals(T1 thing, T ... stuff) {
if(B)
std::cout<<"is integral!"<<std::endl;
else
std::cout<<"is not integral!"<<std::endl;
printIntegrals(stuff ...);
}
template<class T1>
void printIntegrals<{},float>(T1 thing, T ... stuff) {
std::cout<<"is not integral!"<<std::endl;
}
int main() {
bool b;
int i;
double d;
char c;
float f;
printIntegrals(b, i, d, c, f);
}
但是,专用模板未初始化。在编译器错误中,写成:
main.cpp:16:6: error: template-id 'printIntegrals<<expression error> >' used as a declarator
这意味着我遇到了句法问题。这是因为空的初始化列表不是参数包的正确特殊值吗? 以这种方式创建特化的想法似乎是正确的,因为编译器无法实例化以下函数:
main.cpp: In instantiation of 'void printIntegrals(T1, T ...) [with T = {}; T1 = float; bool B = false]' ...
更新:
错误源于我对模板类专门化和函数重载的困惑。感谢评论,我可以创建这个运行示例:
#include <iostream>
#include <type_traits>
template<class T1, bool B = std::is_integral<T1>::value> void printIntegrals(T1 thing) {
if(B)
std::cout<<"is integral!"<<std::endl;
else
std::cout<<"is not integral!"<<std::endl;
}
template<class ... T, class T1, bool B = std::is_integral<T1>::value>
void printIntegrals(T1 thing, T ... stuff) {
if(B)
std::cout<<"is integral!"<<std::endl;
else
std::cout<<"is not integral!"<<std::endl;
printIntegrals(stuff ...);
}
int main() {
bool b{true};
int i{0};
double d{.1};
char c{'a'};
float f{.1};
printIntegrals(b, i, d, c, f);
}