小编per*_*cia的帖子

返回const引用

我对返回const对temporaries的引用的函数声明感到有些困惑.

在以下代码中

#include <string>
#include <iostream>

using namespace std;

const string& foo() { 
    return string("foo"); 
}
string bar() { 
    return string("bar"); 
}

int main() {
    const string& f = foo();
    const string& b = bar();
    cout << b;

}
Run Code Online (Sandbox Code Playgroud)

方法foo和有bar什么区别?

为什么foo要给我warning: returning reference to local temporary object [-Wreturn-stack-address].是不是临时创建的副本const string& f = foo();

c++

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

buillt-in成员的默认初始化

在Bjarne Stroustrup的C++编程语言,第4版,17.6.3.1中说明了这一点

内置成员的"默认初始化"使该成员未初始化.

引用默认编译器生成的构造函数.

但是,在17.6.2中我们有以下代码

struct S {
  string a;
  int b;
};

S f(S arg)
{
  S s0 {};     // default construction: {"",0}
..
}
Run Code Online (Sandbox Code Playgroud)

其中b默认初始化为0.

那么,我在这里错过了什么?

c++ c++11

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

类模板方法特化

我正在尝试专门化这样的模板方法:

template <typename X, typename Y>
class A {
public:
    void run(){};
};


template<typename Y>
void A<int, Y>::run() {}
Run Code Online (Sandbox Code Playgroud)

但我得到

main.cpp:70:17: error: nested name specifier 'A<int, Y>::' for declaration does not refer into a class, class template or class template partial specialization
Run Code Online (Sandbox Code Playgroud)

我知道专业化尚未完成,因为我还没有使用特定的 实例化它Y,但是我该怎么做呢?

c++ templates class template-specialization

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

模板处理方法

假设我想为不同类型的消息设置不同的处理程序,每个消息都由一个标识int.我想将每个处理程序定义为模板方法的实例化.

这个想法是这样的:

handlers.h

enum Handler {
    MESSAGE1,
    MESSAGE2
};

template<MESSAGE1>
void handle() {
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

int main()
{
    handle<Handler::MESSAGE>();
}
Run Code Online (Sandbox Code Playgroud)

当然这段代码不能编译,因为MESSAGE1它不是一个类型.那么,我怎样才能为每条消息创建不同的类型?另外,我想尽可能保持这些类型的使用(因此使用枚举).

c++ templates

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

const 指针作为 std::bind 参数

以下代码

#include <functional>
#include <iostream>

using namespace std;

struct TestStruct {
  int c;
};

int f(int a, int b, const TestStruct **t) { return a + b + (*t)->c; }

void main() {

  TestStruct *t;
  bind(&f, 1, 2, &t)();
}
Run Code Online (Sandbox Code Playgroud)

报告这个错误

error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
note: With the following template arguments:
note: '_Callable=int (__cdecl *&)(int,int,const TestStruct **)'
note: '_Types={int &, int &, TestStruct **&}'
Run Code Online (Sandbox Code Playgroud)

似乎问题在于const TestStruct**参数的常量性。但是,无论是 withconst TestStruct *还是 …

c++ stdbind

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

标签 统计

c++ ×5

templates ×2

c++11 ×1

class ×1

stdbind ×1

template-specialization ×1