加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – const char *,const char(&)[N]和std :: string的函数

发布时间:2020-12-16 10:01:01 所属栏目:百科 来源:网络整理
导读:我想要实现的是具有适用于字符串文字和std :: string的函数的重载,但是为const char *参数产生编译时错误.以下代码几乎完全符合我的要求: #include iostream#include stringvoid foo(const char * str) = delete;void foo(const std::string str) { std::co
我想要实现的是具有适用于字符串文字和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)产生编译时错误而不影响其他重载?

解决方法

此代码执行所需操作(除了数组 – 文字是数组,因此您无法将它们分开)

#include <cstddef>
#include <string>

template <class T>
void foo(const T* const & str) = delete;

void foo(const std::string& str);

template<std::size_t N>
void foo(const char (& str)[N]);

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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读