【发布时间】:2016-01-05 21:38:49
【问题描述】:
我想要实现的是重载适用于字符串文字和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) 产生编译时错误而不影响其他重载?
【问题讨论】:
-
char 数组的类型和字符串字面量的类型之间没有区别,所以你不能没有一个就扔掉一个。但我认为你的其他要求是可以满足的。
-
@Tavian Barns:我想知道,如果有人可以使用字符串文字也是一个常量表达式这一事实(当然你也可以创建一个 constexpr 数组)
标签: c++ string overloading