假设我正在编写一个函数来打印字符串的长度:
template <size_t N>
void foo(const char (&s)[N]) {
std::cout << "array, size=" << N-1 << std::endl;
}
foo("hello") // prints array, size=5
现在我想扩展foo
以支持非数组:
void foo(const char* s) {
std::cout << "raw, size=" << strlen(s) << std::endl;
}
但事实证明,这打破了我最初的预期用途:
foo("hello") // now prints raw, size=5
为什么?这不需要数组到指针的转换,而模板将是精确匹配的吗?有没有办法确保我的数组函数被调用?
https://stackoverflow.com/questions/28243371
复制相似问题