尽管我们有std::max,但我想尝试一下是否可以创建一个接受可变参数并递归调用Max函数来找到最大元素的Max版本。
我在stackoverflow上看到了类似的帖子,但那些帖子都比较旧,并且大多数都在内部使用std::max。由于我遇到了特定的错误,并且使用了更新的编译器,所以这篇帖子不容易重复。
以下是我编写的代码:
我得到的是:
我觉得错误是来自函数调用:
同样,我也感觉我写了很多来实现这个c++20中的
我在stackoverflow上看到了类似的帖子,但那些帖子都比较旧,并且大多数都在内部使用std::max。由于我遇到了特定的错误,并且使用了更新的编译器,所以这篇帖子不容易重复。
以下是我编写的代码:
#include <iostream>
#include <string>
#include <format>
using namespace std::string_literals;
template <typename T>
constexpr T Max(T&& value)
{
return value;
}
template <typename T, typename... Ts>
constexpr T Max(T&& value, Ts&&... args)
{
const T maxRest = Max(args...);
return (value > maxRest) ? value : maxRest;
}
int main()
{
std::cout << std::format("Maximum integer: {}\n", Max(1));
std::cout << std::format("Maximum integer: {}\n", Max(5, 2, 10, 6, 8));
std::cout << std::format("Maximum integer: {}\n", Max("string1", "string2"s)); // error in this line!!
std::cout << std::format("Maximum double: {}\n", Max(3.14, 1.23, 2.56, 0.98));
return 0;
}
我得到的是:
main.cc(79, 21) : error C2440 : 'initializing' : cannot convert from 'std::string' to 'const char (&)[8]'
main.cc(79, 21) : message: Reason: cannot convert from 'std::string' to 'const char [8]'
main.cc(79, 21) : message: No user - defined - conversion operator available that can perform this conversion, or the operator cannot be called
main.cc(87, 55) : message: see reference to function template instantiation 'T Max<const char(&)[8],std::string>(T,std::string &&)' being compiled
with
[
T = const char(&)[8]
]
我觉得错误是来自函数调用:
Max("string1", "string2"s));
。我不知道该怎么解决。同样,我也感觉我写了很多来实现这个c++20中的
Max
函数。有人有什么建议可以将这两个Max
函数合并成一个吗?
Max("string1", "string2"s)
而不是Max("string1"s, "string2"s)
吗? - Ted LyngmoMax("string1", "string2"s)
而不是Max("string1"s, "string2"s)
吗? - Ted LyngmoMax("string1", "string2"s)
而不是Max("string1"s, "string2"s)
吗? - undefinedconst char*
的情况。 - Ted Lyngmoconst char*
的情况。 - Ted Lyngmo