我可以将非类型模板参数传递给重载运算符吗
Can I pass a non-type template argument to an overloaded operator?
我想通过重载()作为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>();
所以,坚持使用命名函数。
您可以将模板放在类上进行管理,如下所示:
template<int i>
class Foo
{
Foo()
{
std::cout << "called overloaded () with " << i << std::endl;
}
static void Get()
{
std::cout << "called get() with " << i << std::endl;
}
};
int main()
{
Foo<1>::Get();
Foo<3>();
return 0;
}
然而,在调用direct()表单时,会构造一个Foo对象,因此会有一点损失
此外,我想你的真实代码在Foo类中还有很多其他东西,所以仅仅为了管理这一点而将模板移动到类中(这可能是一个重大的设计更改)可能是不可接受的。
编辑:
事实上,由于OP可能已经在使用Foo的一个实例,所以我的整个提议都是愚蠢的。不要麻烦。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用