小编son*_*yao的帖子

为什么`int*Get()`被称为`const int&Get()`?

我有一个B有两个方法的类,其中一个返回指向成员变量的指针,另一个返回对该变量的const引用.

我试着打电话给那些方法.在调用期间,我将返回值存储到相应的返回类型.

我期待适当的返回类型最终会调用适当的方法,但我得到一个编译错误说:

error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
   const int& refval2 =  b.Get(); `

这是我的代码:

#include <iostream>
class B{
public:
  int* Get(){
    return &x_;
  }
  const int & Get() const{
    return x_;
  }

private:
  int x_ = 0;
};

int main(){
  B b;
  const int& refval2 =  b.Get(); 
  int* pval2 =  b.Get(); 
}
Run Code Online (Sandbox Code Playgroud)

c++ overload-resolution c++11

4
推荐指数
1
解决办法
149
查看次数

如何在C++中创建临时变量

我有一个函数返回对我的类"记录"的实例的引用.

record& get_record(int key) {
    return lookup(key);
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,它返回一个引用而不是值.现在我稍微修改一下.

record& get_record(int key) {
    if (valid(key))
        return lookup(key);
    else {
        record x;
        x.valid=false;
        return x; //Here I really want to return a temporary variable
                  // and not a reference to a local variable.      
    }
}
Run Code Online (Sandbox Code Playgroud)

返回对局部变量的引用不是一个好主意是否正确?以及如何以一种临时变量的方式返回x?

c++ reference temporary

4
推荐指数
2
解决办法
1816
查看次数

在C++中,st*:: move在T*类型上的意外行为

我有下面的代码段,其中i声明一个称为变量pval,其尝试导出T&&上的T*[与Tint].根据类型信息[使用abi解码],导出的类型是int*.

但是当我比较它的int*类型时,decltype(pval)它返回零而不是1,这意味着它被视为pval不同的类型int*.那么哪一个是由报告的错误pval存在或哪个指示比较为错误.int*typeidis_same

#include<iostream>
#include<string>
#include<typeinfo>
#include<cxxabi.h>
#include<type_traits>

using namespace std;

std::string classname(const std::type_info& info)
{
    int status;
    char* rslt=abi::__cxa_demangle(info.name(),0,0,&status);
    std::string result(rslt);
    free(rslt);
    return result;
}

int main(int argc, char* argv[])
{
    int* ptr = new int(10);
    decltype(std::move(ptr)) pval = std::move(ptr);
    cout << classname(typeid(pval)) << endl;             // as per typeid information the type of pval is …
Run Code Online (Sandbox Code Playgroud)

c++ typeid decltype c++11 value-categories

4
推荐指数
1
解决办法
116
查看次数

调用具有可转换类型的重载函数时的模板化构造函数模糊性

我有2个具有单参数模板化构造函数的类。一个是整数类型的全部,另一个是用于绑定任何可迭代对象的。对于每种类型的特定函数,我都有两个重载。如果我使用整数类型或字符串或对至少一个类有用的函数来调用函数,则会收到有关调用歧义的错误。

#include <string>

class A {
public:
    template <typename Iterable>
    A(Iterable it) : s(it.begin(), it.end()) {} 
private:
    std::string s;
};

class B {
public:
    template <typename Integer>
    B(Integer i) : i(i + 1) {}
private:
    int i;
};

void Use(A a)
{
   // some thing
}

void Use(B b)
{
    // some other thing
}

int main(void)
{
    Use(0);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器似乎对多态集的关注程度还不足以确定确实只有一种可能的解决方案。难道是因为在函数重载之前“解析了”模板吗?如何给编译器一些帮助?

c++ templates constructor overloading overload-resolution

4
推荐指数
1
解决办法
60
查看次数

如何在C中安全地使用枚举?

考虑以下示例:

typedef enum {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday} Day;
void DoSomething(Day day){
//some code
}
Run Code Online (Sandbox Code Playgroud)

问题是以下代码符合:DoSomething(74).那么如何在DoSomething中查看我的参数真的是一天?(依赖于数字将无法工作,因为如果我改变我的枚举Sunday=7....我希望它也能工作,并且检查if(day==Sunday || day ==...)看起来效率低下).

c enums

3
推荐指数
1
解决办法
147
查看次数

私有类型的模板专业化

我有一个通用算法,需要访问其模板类型的特征.有一个特质类可以专门用于提供这些特征.

在我的课程中使用这个算法时,我想将它与类中定义的私有类型一起使用.

但是,专业化只能namespace在我的课程无法访问的范围内或全球范围内发生.

class A
{
    struct Secret 
    {};
};

template <typename T> struct Trait {};

// Inaccessible type ----vvvvvvvvv
template <> struct Trait<A::Secret> // Specialize for  PRIVATE type A::Secret
{ 
    A::Secret magic_value() { return{}; } // ERROR: 'A::Secret': cannot access private struct declared in class 'A'
};  
Run Code Online (Sandbox Code Playgroud)

是否有可能以某种方式使用私有类型专门化模板,至少在可以访问此类型的范围内?

也许有可能将专业化声明为一个friend类?

c++ templates template-specialization

3
推荐指数
1
解决办法
165
查看次数

Return both string and integer from a template function in C++

I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}
Run Code Online (Sandbox Code Playgroud)

and I would like to be able to call it like:

bool bPublisher = getEntry<bool>(node, …
Run Code Online (Sandbox Code Playgroud)

c++ templates if-statement

3
推荐指数
1
解决办法
1262
查看次数

std::vector emplace 和 std::vector emplace 返回成对

我有这个代码:

std::vector<std::pair<const std::string, int>> vec;

vec.emplace_back("a", 1); //success
vec.emplace(vec.end(), "b", 2); //compile error

vec.emplace_back(std::make_pair<const std::string, int>("c", 3));  //success
vec.emplace(vec.end(),
     std::make_pair<const std::string, int>("d", 4)); //compile error
Run Code Online (Sandbox Code Playgroud)

你能解释一下为什么吗?

c++ stl vector c++11 emplace

3
推荐指数
1
解决办法
8097
查看次数

通过string :: insert插入char时出错

我的问题与类似,但那里没有示例代码,我觉得它没有用.

我的错误是

调用类'std :: __ 1 :: __ wrap_iter'的私有构造函数

我的问题的一个最小例子可以在下面找到:

#include <iostream>
#include <string>

using namespace std;

int main(){
    string g = "this_word";
    cout << g << endl;
    char temp = g[0];
    g.erase(0,1);
    cout << g << endl;
    g.insert(0,temp); // Compiler seems to dislike this.  Why?
    cout << g << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我通过两个编译器尝试了这个,并且出现了同样的错误.从标准文档中尽可能多地阅读,但不理解我的错误.

c++ string

3
推荐指数
1
解决办法
42
查看次数

为什么我可以将std :: map的键传递给期望非const的函数?

根据std::map 文档,它存储键值对std::pair<const Key, Value>,因此映射中的键是const.

现在假设我有一个std::map键是指向某些对象的指针.

struct S {};
struct Data {};
using MyMap = std::map<S*, Data>;
Run Code Online (Sandbox Code Playgroud)

我们还假设有一个foo接受S*参数的函数.

void foo(S* ptr) { /* modify the object (*ptr) */ }
Run Code Online (Sandbox Code Playgroud)

现在,问题是:当我MyMap使用基于范围的for循环迭代时,我能够将map元素键传递给foo:

MyMap m = getMyMapSomehow();
for (auto elem : m)
{
    static_assert(std::is_const<decltype(elem.first)>::value, "Supposed to be `const S*`");
    foo(elem.first); // why does it compile?
}
Run Code Online (Sandbox Code Playgroud)

所以,即使我的static_assert成功(所以我假设它的类型elem.firstconst S*),foo编译的调用很好,因此看起来好像我能够修改指针到const后面的对象.

为什么我能做到这一点?

PS这是Coliru …

c++ pointers stl const stdmap

3
推荐指数
1
解决办法
160
查看次数