【问题标题】:Why does type aliasing determine whether output is L-value or R-value?为什么类型别名确定输出是 L 值还是 R 值?
【发布时间】:2018-11-19 16:57:37
【问题描述】:

出于测试目的,我创建了一个包含两个静态函数的结构。 f 的第一个实例在传递 l-value reference 时被调用。传递r-value 时调用第二个实例:

template <typename _Tp>
struct T {
    static constexpr void f(_Tp&) { std::cout <<  "f(T&)  is called!\n"; }
    static constexpr void f(_Tp&&) { std::cout << "f(T&&) is called!\n"; }
};

当我尝试使用strong types 时,我发现第一个实例是在我尝试隐式创建强类型时调用了T::f(_Tp&amp;)。为什么是这样? (见下文)

using T_int = T<int>;

T_int::f(
    typename strong_types::create_strong_type<int, struct tag>(5)()
); // calls f::(T&) (?)

using KG = typename strong_types::create_strong_type<double, struct KG_tag>;
T_int::f(KG(4.2)()); // calls f(T&&)

注意operator()返回的是通过构造函数给出的值。

如果我需要详细说明,请随时询问。

编辑:strong_types 是一个命名空间。它存在于别名 create_strong_type 的其他事物中:

namespace strong_type {
    template <typename T, typename tag>
    using create_strong_type = Strong_Type<T, tag>;

    ...
}

...

template <typename T, typename tag>
struct Strong_Type {
    constexpr explicit Strong_Type(const T& value) : _value(value) {}
    constexpr explicit Strong_Type(T&& value) : _value(std::move(value)) {}

    constexpr T& operator()() noexcept { return _value; }

private:
    T _value;
};

【问题讨论】:

  • strong_types 是什么?
  • 可以,但它是第三方库吗?
  • 哦,我的误解很抱歉。 strong_types 是我自己创建的命名空间。
  • 同样不相关:以下划线开头,后跟大写字母的标识符是保留的,不允许使用。
  • 请修正您编辑中的拼写错误,标识符不匹配,例如strong_typestrong_typesStrong_Type 以及可能 Strong_Type 应该是命名空间的一部分,并且在 create_strong_type? 之前。即使慷慨地移动代码,它也不会像现在这样编译。

标签: c++ reference c++14 lvalue type-alias


【解决方案1】:

差异不是由于使用别名 (using),而是由于您作为第一个模板参数传递给 create_strong_type 的类型。一种情况是int,另一种情况是double

试试T&lt;double&gt;::f(KG(4.2)());,你会看到参数作为左值引用传递(因为Strong_Type::operator()的返回类型是T&amp;)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-01
    • 2011-08-23
    • 1970-01-01
    • 2017-10-12
    • 2023-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多