【问题标题】:Why aren't placeholders for std::bind implemented using non-type template parameters?为什么不使用非类型模板参数实现 std::bind 的占位符?
【发布时间】:2016-08-09 16:03:18
【问题描述】:

我知道这个问题是相当理论化的,但我认为如果将占位符定义为模板,例如:

namespace std { 
   namespace placeholders {
      template <size_t> struct placeholder { constexpr placeholder() {}; }; 
      template <size_t N> constexpr placeholder<N> _{};
   }
}

有用法:

std::bind(foo, std::placeholders::_<1>, std::placeholders::_<2>); 

或者对于 c++11:

namespace std { 
   namespace placeholders {
      template <size_t> struct _ { }; 
   }
}

有用法:

std::bind(foo, std::placeholders::_<1>{}, std::placeholders::_<2>{});

代码不会失去其清晰性,我们将能够使用它进行一些花哨的元编程。那么...为什么不使用非类型模板参数实现 std::bind 的占位符?

【问题讨论】:

  • 该语法看起来不合法。 _&lt;1&gt; 仍然是一种类型,并且您不能将类型作为值传递:您至少需要 _&lt;1&gt;{},不是吗?还是template&lt;size_t&gt; struct placeholder {constexpr placeholder() {};}; template&lt;size_t N&gt; constexpr placeholder&lt;N&gt; _{};?当你到达第二个时,你需要变量模板,这在 C++11 中不存在。那么,你想知道什么?

标签: c++ templates c++14 template-meta-programming stdbind


【解决方案1】:

C++11 中不存在变量模板,这是将std::bind 添加到语言中的地方。

_1 名称很短,取自 booststd::bind 是在其中开发的。

您可以轻松编写自己的类似占位符。

namespace my_placeholders {
  template <int> struct placeholder { constexpr placeholder() {}; }; 
  template <int N> constexpr placeholder<N> _{};
}
namespace std {
  template<int N>
  struct is_placeholder< ::my_placeholders::placeholder<N> >:
    std::integral_constant<int, N>
  {};
}

现在my_placeholders::_&lt;1&gt; 是一个有效的std::bind 占位符,在各个重要方面都等效于_1

考虑到这样做的能力,坦率地说,与 lambda 相比,使用 std::bind 是多么烦人,我可以看到没有人会费心将这样的功能实际添加到标准 C++14 后。

【讨论】:

    猜你喜欢
    • 2020-03-12
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多