Skip to content

Instantly share code, notes, and snippets.

@maxco2
Last active May 25, 2018 07:52
Show Gist options
  • Select an option

  • Save maxco2/587bfc331e5e19718abc477cf3d06b15 to your computer and use it in GitHub Desktop.

Select an option

Save maxco2/587bfc331e5e19718abc477cf3d06b15 to your computer and use it in GitHub Desktop.
C++奇技淫巧!!!

ADL奇技淫巧

缘起

v2ex帖子

利用adl改造

深入

namespace NS
{
    struct Test{};
    void f(int){}
    void f(Test){}
}
int main()
{
    f(1);//error
    f(NS::Test());//works,because of ADL
}

应用

template<unsigned P> struct priority : priority<P-1> {};
template<> struct priority<0> {};

template<class T>
auto checkNamespaceFuncWithADL(T i,priority<1>) -> decltype(f(i)) { f(i); }

template<class T>
void checkNamespaceFuncWithADL(T i,priority<0>) { static_assert(sizeof(T)==0,"couldn't find a function f in T namespace"); }

template<class T>
void checkNamespaceFuncWithADL(T i){checkNamespaceFuncWithADL(i,priority<1>{});}

namespace NS
{
    struct Test{};
}
void f(NS::Test){std::cout<<"HAHA";}
int main()
{
    checkNamespaceFuncWithADL(NS::Test());//error
}
template<unsigned P> struct priority : priority<P-1> {};
template<> struct priority<0> {};

template<class T>
auto checkNamespaceFuncWithADL(T i,priority<1>) -> decltype(f(i)) { f(i); }

template<class T>
void checkNamespaceFuncWithADL(T i,priority<0>) { static_assert(sizeof(T)==0,"couldn't find a function f in T namespace"); }

template<class T>
void checkNamespaceFuncWithADL(T i){checkNamespaceFuncWithADL(i,priority<1>{});}

namespace NS
{
    struct Test{};
    void f(Test){std::cout<<"HAHA";}
}
int main()
{
    checkNamespaceFuncWithADL(NS::Test());//works!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment