我开始关注std::common_type
并且不确定它的用途和功能.有些事情让我觉得奇怪:
common_type<Foo, Bar, Baz>
可能与之不同common_type<Baz, Foo, Bar>
.要么可以编译,要么可能没有.虽然从common_type
定义的方式来看这很清楚,但它感觉奇怪且不直观.这是因为缺乏通用解决方案还是打算?common_type
实际编译?可能是专门的is_convertible
还不够common_type
?在这样的情况下仍然无法找出常见类型:
struct Baz;
struct Bar { int m; };
struct Foo { int m; };
struct Baz { Baz(const Bar&); Baz(const Foo&); };
Run Code Online (Sandbox Code Playgroud)
建议的解决方案是专业化common_type
,这是繁琐的.有更好的解决方案吗?
有关参考,请参见N3242中的§20.9.7.6表57.
如果没有声明constexpr
,std::forward
将丢弃constexpr-ness以用于转发参数的任何函数.为什么std::forward
不宣布constexpr
自己这样可以保留constexpr-ness?
示例:(使用g ++ snapshot-2011-02-19测试)
#include <utility>
template <typename T> constexpr int f(T x) { return -13;}
template <typename T> constexpr int g(T&& x) { return f(std::forward<T>(x));}
int main() {
constexpr int j = f(3.5f);
// next line does not compile:
// error: ‘constexpr int g(T&&) [with T = float]’ is not a constexpr function
constexpr int j2 = g(3.5f);
}
Run Code Online (Sandbox Code Playgroud)
注意:从技术上讲,很容易制作std::forward
constexpr,例如,如此(请注意,g std::forward
已被替换为fix::forward
):
#include <utility>
namespace fix …
Run Code Online (Sandbox Code Playgroud)