就像这个主题中的问题:是否有一种方法可以从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)
当然,我提供了一个额外的运算符:
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)`。
std::initializer_list<T>
并写成if ({val_1, val_2, val_3} == value)
,但是请不要在你不拥有的类型上重载运算符。 - Justin