如何从重载集中删除当前函数
How to remove the current function from the overload set?
我的命名空间中有一个函数,ns::foo
,其工作是使用依赖于参数的查找来调度对foo
的调用:
namespace ns
{
template<typename T>
void foo(T x)
{
// call foo through ADL
foo(x);
}
}
我希望客户端能够调用foo
而无需手动实例化它,即:
bar x;
ns::foo(x);
不
ns::foo<bar>(x);
当然,问题是,如果没有比ns::foo
更好的匹配foo
,ns::foo
就是递归的。
我不想给ns::foo
一个不同的名字,那么有没有办法把它从自身内部的过载中移除呢?
如果要调度到的foo
不在 ns
命名空间中,那么这应该有效:
namespace helper
{
template<typename T>
void _foo(T x)
{
// call foo through ADL
foo(x);
}
}
namespace ns
{
template<typename T>
void foo(T x)
{
::helper::_foo(x);
}
}
诀窍是,从_foo
调用foo
不会考虑ns::foo
,因为它不在依赖于参数的命名空间中。当然,除非x
的类型恰好是ns
,但根据定义,您有一个递归。
更新:您必须将此代码放在namespace ns
的定义之后:
namespace ns
{
//your useful stuff here
}
namespace helper { /* template _foo */ }
namespace ns { /* template foo */ }
没有递归,因为 helper::_foo
函数无法调用template foo
,因为它仍未定义。
如果使用额外的参数定义 ADL 函数,则会为其提供不同类型的签名,因此不会发生冲突。我在全局范围内定义了模板,但它也可以在ns
范围内工作。
namespace ns
{
class A {};
class B {};
void foo(A, int) { std::cout << "adl: fooA" << std::endl; }
void foo(B, int) { std::cout << "adl: fooB" << std::endl; }
}
template <typename T>
void foo(T t) {
foo(t, 0);
}
int main()
{
ns::A a;
ns::B b;
foo(a); //calls ns::foo
foo(b); //calls ns::foo
}
相关文章:
- 如何通过 getter 函数删除矢量的元素?
- C++类析构函数删除成员(如果"owner"?
- 使用私有析构函数删除动态分配的对象
- C ++(为什么)确实移动构造函数删除运算符=
- 析构函数删除错误的元素
- C++ 类析构函数删除部分但不是全部成员数据
- 如何使用 deleteEntry 函数 c++ 删除数组中的单个字符串
- 仅仅以避免隐式复制构造函数删除,使用shared_ptr而不是unique_ptr作为类成员明智
- 析构函数删除在 main 中声明的动态数组
- 如果未分配申报表,是否需要删除或处理动态数组?还是它被函数删除
- C++ 函数删除一行
- g++空函数删除是否递归工作
- C++析构函数删除东西(对象,指针?)太快
- C++析构函数删除包含动态数组作为数据成员的对象时的用法
- C++11 析构函数 = 删除
- 父类析构函数删除具有外部启动元素的子类
- 函数删除太多
- C++析构函数删除共享内存
- C++,如何让此函数删除存储在数组中的字符串
- 析构函数删除数组时出错