gpt4 book ai didi

c++ - 我可以将非类型模板参数传递给重载运算符吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:43 26 4
gpt4 key购买 nike

我想通过将 () 重载为 getter 方法来为类添加一些语法糖。但是,getter 方法采用非类型模板参数。考虑一个简单的测试用例:

#include <iostream>

class Foo
{
public:
template <int i> void get()
{
std::cout << "called get() with " << i << std::endl;
}
template <int i> void operator()()
{
std::cout << "called overloaded () with " << i << std::endl;
}
};

int main()
{
Foo foo;
foo.get<1>();
foo.get<2>();
foo<3>(); // error: no match for ‘operator<’ in ‘foo < 3’
return 0;
}

如果 foo<3>();,这将按预期编译和运行被注释掉了。 C++ 语法是否支持我正在尝试做的事情,或者我应该放弃并坚持为 getter 使用命名方法?

最佳答案

您正在寻找的语法存在,但您不会喜欢它:

foo.operator()<3>();

所以,坚持使用命名函数。

关于c++ - 我可以将非类型模板参数传递给重载运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9115789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com