简体   繁体   English

元编程的C ++ STL功能等效项

[英]C++ STL functional equivalents for metaprogramming

Are there constexpr or other compile time equivalents to the STL functional and other libraries for use with metaprogramming? 是否有与STL函数库和其他库一起使用的constexpr或其他编译时等效项与元编程一起使用? More specifically, I am trying to write some metaprograms that use SFINAE to evaluate some conditional and generate the corresponding types. 更具体地说,我正在尝试编写一些使用SFINAE评估某些条件并生成相应类型的元程序。 Example: 例:

template<int A, int B>
enable_if_t<(A < B)> my_func() {// do something 
}

template<int A, int B>
enable_if_t<!(A < B)> my_func() {// do nothing 
}

Ideally I would like the user to be able to pass in a comparator (like std::less<int> ), rather than hard coding it to < . 理想情况下,我希望用户能够传递比较器(例如std::less<int> ),而不是将其硬编码为< So something like: 所以像这样:

template<int A, int B, class comp = std::less<int>>
enable_if_t<comp(A, B)> my_func() {// do something 
}

template<int A, int B, class comp = std::less<int>>
enable_if_t<comp(A, B)> my_func() {// do nothing 
}

However since the functional objects are not constant expressions, they are not getting evaluated at compile time and so this does not work. 但是,由于功能对象不是常量表达式,因此在编译时不会对它们进行求值,因此这是行不通的。 What would be the right way to implement something like this? 什么是实现这样的正确方法?

std::less<int>(int, int) is not a constructor for std::less . std::less<int>(int, int)不是std::less的构造函数。 The only constructor for std::less is () (I prefer using {} , because it makes it clear I'm constructing something). std::less的唯一构造函数是() (我更喜欢使用{} ,因为很明显我正在构造某些东西)。

Since C++14 it has a constexpr operator() that (if < on the types involved is constexpr ) can be evaluated at compile time. 从C ++ 14开始,它具有constexpr operator() (如果所涉及类型上的<constexpr )可以在编译时求值。

Thus: 从而:

template<int A, int B, class comp = std::less<int>>
enable_if_t<comp{}(A, B)> my_func() {// do something 
}

template<int A, int B, class comp = std::less<int>>
enable_if_t<!comp{}(A, B)> my_func() {// do nothing 
}

should work. 应该管用。

In C++11 在C ++ 11中

namespace notstd {
  template<class T=void>
  struct less {
    constexpr bool operator()(T const& lhs, T const& rhs)const{
      return lhs<rhs;
    }
  };
  template<>
  struct less<void> {
    template<class T, class U>
    constexpr bool operator()(T const& lhs, U const& rhs)const{
      return lhs<rhs;
    }
    // maybe also add this:
    //struct is_transparent {};
  }
}

(assuming your < on your system is a total order on pointers) should work (replacing std::less<T> with notstd::less<T> ). (假设您的<在系统上是指针的总顺序)应该可以工作(将std::less<T>替换为notstd::less<T> )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM