多年后我又回到了 C++,并试图掌握其中的概念。我编写了一个简单的测试代码,但出现了一个错误,我不太明白为什么会出现在这里。
template <typename T, typename U>
concept addable = requires (T a, U b)
{
a + b;
};
template <typename T>
T test_add(T&& value)
{
return value;
}
template <typename T, typename... Args>
auto test_add(T&& value, Args&&... rest) requires addable<T, decltype(test_add(forward<Args>(rest)...))>
{
return value + test_add(forward<Args>(rest)...);
}
目标是检查返回表达式上是否有有效的+操作,但是当我像这样调用函数时:
auto result = test_add(1, 3, 5);
我收到以下错误:“没有重载函数“test_add”的实例与参数列表匹配”。
这里出了什么问题?
看起来您希望
concept
是可变参数,因此您需要一个参数包,然后进行包扩展:
template <class... Ts>
concept addable = requires(Ts&&... ts) { (... + ts); };
您的
test_add
函数模板可以替换为 one,它使用 concept
并在 +
运算符上使用折叠表达式:
auto test_add(addable auto&&... values) {
return (... + std::forward<decltype(values)>(values));
}