通过ADL从另一个函数调用一个函数
Calling a function by ADL from another function
我有一个关于ADL在一般情况下如何发现类型的问题。具体来说,我有一些"通用"代码,我需要在编译时检查应该由ADL找到的函数的存在。例如:
#include "MyClass.h"
struct MyClass
{
friend inline void DoSomething(MyClass& first, MyClass& second){}
}
MyClass a, b;
DoSomething(a,b); //DoSomething in MyClass will be found by ADL
我有一个trait类,它使用'sizeof技巧'来检查这个ADL函数的存在:
//HasDoSomething.h
//type trait to check whether a type has a DoSomething function defined
template<typename T>
struct has_doSomething
{
typedef char yes;
typedef char (&no)[2];
//SFINAE eliminates this when the type is invalid
template <typename U, U>
struct Check;
template <typename U>
static yes Tester(Check<void(*)(U&, U&), &DoSomething>*);
//overload resolution prefers anything at all over ...
template <typename U> static no Tester(...);
static bool const value = sizeof(Tester<T>(0)) == sizeof(yes);
};
trait class/sizeof技巧本身并不重要(如果您感兴趣,可以在《c++ Template Metaprogramming》一书中找到详细信息)。相反,问题在于除非我在定义了DoSomething(例如
)的(任意)类型的 #include之后#include它,否则该类型trait将无法编译。#include "MyClass.h"
#include "HasDoSomething.h"
或者我用DoSomething函数声明创建一个虚拟类:
struct DummyClass
{
public:
friend inline void DoSomething(DummyClass&, DummyClass&);
private:
DummyClass(){}
};
并将其(直接或通过Dummy.h)包含到HasDoSomething.h中。通过强制#include的顺序或插入冗余代码来踢ADL查找似乎并不理想,所以我是否误解了什么或做错了什么?
ADL仅用于确定函数调用的重载集。
在编译器可以这样做之前,它必须首先确定这是一个函数调用,通过执行正常的名称查找并找到一个函数。
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何仅为一个函数添加延迟
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 我需要将多个函数组合为一个函数
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 编写一个函数以使用 n 百分比的 CPU 使用率
- 将 N-arg 函数包装到另一个函数中
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- C++从另一个函数退出函数
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 视觉我希望一个函数在另一个函数C++中进行计算
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 在另一个函数 (c++) 中调用变量
- 如何在另一个函数中使用返回值作为参数?
- 如何包装一个函数以适应另一个函数的所需类型
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针