我有这个代码
#include <iostream>
#include <type_traits>
enum class Color: char { Red = 'r', Yellow = 'y', Green = 'g' };
template<Color color>
auto say_my_name(unsigned times = 1) {
for (unsigned i = 0; i < times; i++) {
std::cout << static_cast<std::underlying_type_t<Color>>(color) << ' ';
}
std::cout << std::endl;
}
constexpr auto say_red = say_my_name<Color::Red>;
int main()
{
say_my_name<Color::Yellow>(3);
say_my_name<Color::Yellow>();
say_red(2);
say_red(); // too few arguments to function
}
我希望该函数say_red
是 的特化say_my_name
,因此我可以轻松地在我的代码中调用它,而无需一直提供模板参数。
say_red(2)
工作正常,但say_red()
不会编译并显示错误消息“错误:函数的参数太少”
有没有办法让我的代码在不指定参数的情况下编译?
作为旁注:如果可以解决问题,我也可以将模板参数转换为函数参数。我的问题是,这std::bind
不在constexpr
C++17 中,所以这不适合我。
此外,我不想在每个声明中指定默认参数say_*
。你可以想象,这是一个例子,我的“现实生活”枚举有 8 个变体,所以我想写尽可能少的代码。
默认参数在调用站点被替换。它们不是函数类型的一部分。因此,您需要“某物”来启用say_red
. 您可以使用 lambda:
#include <iostream>
#include <type_traits>
enum class Color: char { Red = 'r', Yellow = 'y', Green = 'g' };
template<Color color>
auto say_my_name(unsigned times = 1) {
for (unsigned i = 0; i < times; i++) {
std::cout << static_cast<std::underlying_type_t<Color>>(color) << ' ';
}
std::cout << std::endl;
}
constexpr auto say_red = [](unsigned times = 1){
say_my_name<Color::Red>(times);
};
int main()
{
say_my_name<Color::Yellow>(3);
say_my_name<Color::Yellow>();
say_red(2);
say_red(); // too few arguments to function
}
如果您不介意()
在每次调用时添加一个,您可以使用函子:
#include <iostream>
#include <type_traits>
enum class Color: char { Red = 'r', Yellow = 'y', Green = 'g' };
template<Color color>
struct say_my_name {
void operator()(unsigned times = 1) const {
for (unsigned i = 0; i < times; i++) {
std::cout << static_cast<std::underlying_type_t<Color>>(color) << ' ';
}
std::cout << std::endl;
}
};
using say_red = say_my_name<Color::Red>;
int main()
{
say_my_name<Color::Yellow>()(3);
say_my_name<Color::Yellow>()();
say_red()(2);
say_red()(); // too few arguments to function
}
如果你不喜欢额外的,()
你可以这样做:
using say_red = say_my_name<Color::Red>;
constexpr auto red_say = say_red{};
int main()
{
red_say(2);
red_say(); // too few arguments to function
}
请注意,您也可以使用构造函数代替operator()
,但 usingoperator()
更灵活,因为它允许您返回一个值。关键是分两步进行特化和重载解析(特化函子然后operator()
用一个或零个参数调用)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句