我正在尝试编写一个可以打印堆栈和队列的函数,我的代码如下
template<typename Cont>
void print_container(Cont& cont){
while(!cont.empty()){
if(std::is_same<Cont, stack<int>>::value){
auto elem = cont.top();
std::cout << elem << '\n';
} else {
auto elem = cont.front();
std::cout << elem << '\n';
}
cont.pop();
std::cout << elem << '\n';
}
}
int main(int argc, char *argv[])
{
stack<int> stk;
stk.push(1);
stk.push(2);
stk.push(3);
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
std::cout << "print stack" << endl;
print_container(stk);
std::cout << "print queue" << endl;
print_container(q);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但它在这里不起作用,错误信息是:
demo_typeof.cpp:35:30: error: no member named 'front' …Run Code Online (Sandbox Code Playgroud) #include <array>
template<typename T>
void Func(T Param)
{
int Val = 0;
if (std::is_same<T, bool>::value)
Val += Param ? 1 : 0;
}
int main()
{
std::array<int, 10> A;
Func(A);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我用gcc或MSVC编译时,我得到:
Error C2440 '?': cannot convert from 'std::array<int,10>' to 'bool'
不应该编译器甚至不编译,Val += Param ? 1 : 0;因为std::is_same<std::array<int, 10>, bool>::value是0?