gpt4 book ai didi

c++ - 通过 ADL 从另一个函数调用一个函数

转载 作者:行者123 更新时间:2023-11-28 07:48:10 25 4
gpt4 key购买 nike

我有一个关于 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

我有一个特征类,它使用“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 一书中找到详细信息,我从中提取了它)。相反,问题是这种类型特征不会编译,除非我在一个(任意)类型的#include 之后#include 它 确实定义了 DoSomething,例如

#include "MyClass.h"
#include "HasDoSomething.h"

或者我创建一个带有 DoSomething 函数声明的虚拟类:

struct DummyClass
{
public:
friend inline void DoSomething(DummyClass&, DummyClass&);
private:
DummyClass(){}
};

并将其包含(直接或通过 Dummy.h)到 HasDoSomething.h 中。通过强制执行 #includes 的顺序或插入冗余代码来启动 ADL 查找似乎并不理想,所以我是误会了什么还是做错了什么?

最佳答案

ADL 仅用于确定函数调用的重载集。
在编译器可以这样做之前,它必须首先确定这是一个函数调用,方法是进行正常的名称查找并找到一个函数。

关于c++ - 通过 ADL 从另一个函数调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425774/

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