Search code examples
c++templatesc++14template-meta-programmingstdbind

Why aren't placeholders for std::bind implemented using non-type template parameters?


I know the question is rather theoretical but I think if placeholders would be defined as the template like e.g.:

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

with usage:

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

Or for c++11:

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

with usage:

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

the code wouldn't loose anything of its clearness and we would be able to do some fancy metaprogramming using it. So... why aren't placeholders for std::bind implemented using non-type template parameters?


Solution

  • Variable templates did not exist in C++11, which is where std::bind was added to the language.

    The _1 names where short, and taken from boost where std::bind was developed.

    You can write your own similar placeholders easily.

    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>
      {};
    }
    

    and now my_placeholders::_<1> is a valid std::bind placeholder equivalent to _1 in every important way.

    Given the ability to do this, and frankly how annoying it is to work with std::bind in comparison to lambda, I could see nobody bothering to actually add such a feature to the standard post C++14.