我见过这样的代码:
struct foo_functor {
template <typename T, typename U>
constexpr auto operator()(T t, U u) const -> decltype(t | u) {
return t | u;
}
};
constexpr foo_functor foo;
Run Code Online (Sandbox Code Playgroud)
据我所知,它与以下内容相同:
template <typename T, typename U>
constexpr auto foo(T t, U u) -> decltype(t | u) {
return t | u;
}
Run Code Online (Sandbox Code Playgroud)
为什么要做第一个?有什么区别吗?据我从编译器输出中看到,至少在constexpr,没有。如果不是constexpr,那会不会有什么不同呢?
编辑:请注意,与第一个示例非常相似的代码似乎被用来代替普通函数。6 种不同的结构,都只有operator()模板,都像示例的最后一行一样被实例化。然后每个都像正常功能一样使用。
我正在实现一个简单的智能指针类,我决定在完成后制作我自己的std::make_unique/std::make_shared函数版本以配合它。我创建了这两个重载:
// note: Box<T> is my "unique pointer" type, it has a partial specialization for T[],
// and it works as expected when created outside of these functions
template <class T, class... Args> Box<T> make_box(Args &&... args) {
auto ptr = new T(std::forward<Args>(args)...);
return Box<T>(std::move(ptr));
}
template <class T> Box<T> make_box(std::size_t size) {
auto ptr = new std::remove_extent_t<T>[size];
return Box<T>(std::move(ptr));
}
Run Code Online (Sandbox Code Playgroud)
第一个重载工作得很好,至少在这个例子中:
struct Point3D {
double x, y, z;
Point3D() = default;
Point3D(double x, double y, …Run Code Online (Sandbox Code Playgroud)