我想要实现的是函数的重载功能,适用于字符串字面量和std::string
,但对于const char*
参数会产生编译时错误。以下代码几乎可以满足我的需求:
#include <iostream>
#include <string>
void foo(const char *& str) = delete;
void foo(const std::string& str) {
std::cout << "In overload for const std::string& : " << str << std::endl;
}
template<size_t N>
void foo(const char (& str)[N]) {
std::cout << "In overload for array with " << N << " elements : " << str << std::endl;
}
int main() {
const char* ptr = "ptr to const";
const char* const c_ptr = "const ptr to const";
const char arr[] = "const array";
std::string cppStr = "cpp string";
foo("String literal");
//foo(ptr); //<- compile time error
foo(c_ptr); //<- this should produce an error
foo(arr); //<- this ideally should also produce an error
foo(cppStr);
}
我不是很满意它可以编译 char 数组变量,但如果我想接受字符串字面量的话,我认为没有其他办法(如果有,请告诉我)。
然而,我想避免的是 std::string
重载接受 const char * const
变量。不幸的是,我不能只声明一个删除的重载,该重载带有一个 const char * const&
参数,因为这也会匹配字符串字面量。
你有什么想法,如何使 foo(c_ptr)
产生编译时错误,而不影响其他重载?