【问题标题】:Calling a function by ADL from another function通过 ADL 从另一个函数调用一个函数
【发布时间】:2013-01-20 14:59:17
【问题描述】:

我有一个关于 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 after 定义了 DoSomething 的(任意)类型的#include,例如,

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

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

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

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

【问题讨论】:

  • 对不起,我的错误。但是,&DoSomething 会给出错误 C2065: 'DoSomething' : undeclared identifier,除非我将 DummyClass 及其友元函数包括在内。

标签: c++ namespaces argument-dependent-lookup


【解决方案1】:

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

【讨论】:

  • 谢谢,所以我使用虚拟类的策略是可以接受的/在这种特定情况下唯一的方法?
  • 是的,但您甚至可以在 struct has_DoSomething 的声明之前添加一个 void DoSomething(); 声明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
相关资源
最近更新 更多