有没有办法从`std :: initializer_list`创建用户定义的文字?

时间:2018-12-17 17:05:58

标签: c++ literals initializer-list

就像主题中一样:是否有一种方法可以从std::initializer_list创建用户定义的文字?

我正在尝试做类似的事情:

template <typename T> inline
std::initializer_list<T> const & operator "" _lit(std::initializer_list<T> const & list)
{
    return std::move(list); // I am not sure, but this line might cause undefined behavior... well I'll think about it latter...
}

int main()
{
    { 10, 20, 30, 40 }_lit // Error: identifier '_lit' is undefined;

    return 0;
}

但是似乎编译器无法理解我正在尝试调用operator""_lit({10, 20, 30, 40});,有什么办法可以解决它?


编辑:
很抱歉,事实证明这只是XY问题的另一个例子...
让我详细说明

我正在尝试“扩展”当前的C ++语法(这是一个有趣的小项目...)

主要思想是简化此过程:

if ((val_1 == value) && (val_2 == value) && (val_3 == value)) { /* ... */ }

陷入困境:

if (std::initializer_list<T>{val_1, val_2, val_3} == value)

ofc我要提供一个附加的运算符:

template <typename T> inline
bool operator==(std::initializer_list<T> const & list, T const & ref)
{
    for (auto const & element : list)
    {
        if (element == ref) { /* Do nothing. */ }
        else
        {
            return false;
        }
    }
    return true;
}

一切都会很好,但是我不喜欢在大括号前键入std::initializer_list<T>……否则,编译器选择了operator==()的默认版本,我得到了一个编译错误...

来到这里是为了将if (std::initializer_list<T>{val_1, val_2, val_3} == value)更改为if ({val_1, val_2, val_3}_lit == value)

4 个答案:

答案 0 :(得分:1)

您不能为std::initializer_list设置用户定义的文字。幸运的是,尽管C ++ 17提供了一个非常酷的新工具,但可以帮助我们。 Class template argument deduction允许我们仅使用类模板的名称,并且编译器将确定模板参数需要是什么,因此我们不必指定它们。这意味着您可以利用std::array,您的代码将变成

template<typename T, std::size_t N>
bool operator==(std::array<T, N> const & list, T const & ref)
{
    for(auto const& e : list)
        if (e != ref)
            return false;
    return true;
}

int main()
{
    using std::array;
    if (array{4,4,4,4,4} == 4)
        std::cout << "all 4";
}

除了using语句,它只是_litarray之间的一个额外字符

答案 1 :(得分:1)

来自评论:

  

@NathanOliver我正在尝试“扩展”当前的C ++语法(这很有趣   小项目...)的主要思想是简化此过程:if(((val_1 ==   值)&&(val_2 ==值)&&(val_3 ==值))到此:如果   (std :: initializer_list {val_1,val_2,val_3} ==值)(带有   重载运算符:bool operator ==(std :: initializer_list const&   列表,T const&ref))...我想省略我需要在其中的部分   键入std :: initializer_list,我发现我可以更改它   变成习惯上的文字

因此,您似乎需要这样的东西:

template<typename T>
bool allEqualTo(T a, T b)
{
    return a == b;
}

template<typename T, typename... TArgs>
bool allEqualTo(T a, T b, TArgs... args)
{
    return allEqualTo(a, b) && allEqualTo(a, args...);
}

if (allEqualTo(value, val_1, val_2, val_3)) {
    ....
}

答案 2 :(得分:1)

如果您使用范围库,则可以只使用all_of

// Using Range-v3: https://ericniebler.github.io/range-v3/index.html
if (ranges::v3::all_of({val_1, val_2, val_3},
    [value](auto const& other) { return value == other; })) {
    // ...
}

您可以使用助手来进一步简化它:

// Note: Prior to C++17, this could lead to ODR violations.
// After C++17, this will be an inline variable, thus this is fine.
// If using in C++14 or before, write std::equal_to<>{} instead of std::equal_to{}.
constexpr auto equal_to = boost::hof::partial(std::equal_to{});

// ...

if (ranges::v3::all_of({val1, val_2, val_3}, equal_to(value))) {
    // ...
}

Demo

答案 3 :(得分:1)

template<class T, std::size_t N>
struct any_of:std::array<T, N> {
  #define MAKE_OPERATOR( OPERATOR ) \
    template<class U, \
      std::enable_if_t< std::is_same<void, std::void_t< \
        decltype( std::declval<T const&>() == std::declval<U const&>() ) \
      >>{}, bool> =true \
    > \
    friend bool operator OPERATOR ( any_of const& lhs, U const& rhs) { \
      return std::any_of( \
        lhs.begin(), lhs.end(), \
        [&](auto&& lhs){ return lhs OPERATOR rhs; } \
      ); \
    } \
    template<class U, \
      std::enable_if_t< std::is_same<void, std::void_t< \
        decltype( std::declval<U const&>() == std::declval<T const&>() ) \
      >>{} && !std::is_same< U, any_of >{} , bool> =true \
    > \
    friend bool operator OPERATOR ( U const& lhs, any_of const& rhs) { \
      return std::any_of( \
        rhs.begin(), rhs.end(), \
        [&](auto&& rhs){ return lhs OPERATOR rhs; } \
      ); \
    }
  MAKE_OPERATOR(==)
  MAKE_OPERATOR(!=)
  MAKE_OPERATOR(<)
  MAKE_OPERATOR(<=)
  MAKE_OPERATOR(>=)
  MAKE_OPERATOR(>)
  #undef MAKE_OPERATOR
  explicit any_of( std::array<T, N> arr):std::array<T, N>(std::move(arr)) {}
  template<class...Ts>
  explicit any_of( T t, Ts... ts ):std::array<T, N>{ std::move(t), std::move(ts)... } {}
  any_of( any_of const& )=delete;
  any_of& operator=( any_of const& )=delete;
  any_of()=delete;
};
template<class T, std::size_t N>
any_of(T(&)[N]) -> any_of<T,N>;
template<class T, class...Ts>
any_of(T, Ts...) -> any_of<T, 1+sizeof...(Ts)>;

测试代码:

if (any_of{1,2,3} == 2) {
    std::cout << "2 is there\n";
}
if (! (any_of{1,2,3} == 7) ){
    std::cout << "7 is not there\n";
}

if (any_of{1,2,3} == any_of{5,6,1}) {
    std::cout << "overlap!\n";
}
if (!(any_of{1,2,3} == any_of{5,6,7})) {
    std::cout << "no overlap!\n";
}

Live example

编译器中的输出:

2 is there
7 is not there
overlap!
no overlap!

所有比较运算符均受支持。

交叉类型的double any_of,例如:

any_of{1,2,3} == any_of{3.14, 5.7, 1.0}

由于两个==中的两个any_of都将无法编译。