小编Kor*_*ory的帖子

为什么编译器要求指定类型?

我实现了一个类模板,该类模板负责构造单个类型(遵循构建器模式)。构建器的构造函数用于推导两种类型。

下面是一个演示该问题的示例(使用编译器资源管理器)。我将clang 6与-std = c ++ 17一起使用。

#include <utility>

template <typename T>
struct builder
{
    explicit builder(T& _t);
    auto option(int x) -> builder&;
    auto build() -> int;
};

template <typename T>
void build_it(T& _t, int _u)
{
    // Why does the line below not compile?
    // C++17 compilers should be able to deduce the type, right?
    auto obj = builder{_t}.option(_u).build();
}
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误消息。


x86-64 clang 6.0.0 (Editor #1, Compiler #1) C++
x86-64 clang 6.0.0

-std=c++17 -O2 -Wall -Wextra
1
<Compilation failed> …
Run Code Online (Sandbox Code Playgroud)

c++ templates type-deduction c++17

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

非常量成员引用在 const 对象上是可变的吗?

鉴于以下情况:

struct S
{
    int x;
    int& y;
};

int main()
{
    int i = 6;
    const S s{5, i}; // (1)
    // s.x = 10;     // (2)
    s.y = 99;        // (3)
}
Run Code Online (Sandbox Code Playgroud)

为什么什么时候(3)允许?sconst

(2)产生编译器错误,这是预期的。我预计也会(3)导致编译器错误。

c++ struct reference class member

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

标签 统计

c++ ×2

c++17 ×1

class ×1

member ×1

reference ×1

struct ×1

templates ×1

type-deduction ×1