【发布时间】: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&)。为什么是这样? (见下文)
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_type与strong_types和Strong_Type以及可能Strong_Type应该是命名空间的一部分,并且在create_strong_type? 之前。即使慷慨地移动代码,它也不会像现在这样编译。
标签: c++ reference c++14 lvalue type-alias