Skip to content

Instantly share code, notes, and snippets.

@loliGothicK
Last active February 11, 2016 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loliGothicK/66b2fe424ecfb62f69dd to your computer and use it in GitHub Desktop.
Save loliGothicK/66b2fe424ecfb62f69dd to your computer and use it in GitHub Desktop.
decltypeとSFINAEによるオーバーロード条件分岐 ref: http://qiita.com/_EnumHack/items/e831a359338e5f134325
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
template < typename Container >
auto my_find(Container& c, typename Container::key_type key)
->decltype((c.find(key)))
{
std::cout << "member" << std::endl;
return (c.find(key));
}
template < typename Container >
decltype(auto) my_find(Container& c, typename Container::value_type v)
{
std::cout << "free" << std::endl;
return (std::find(c.begin(),c.end(), v)) ;
}
int main(){
std::vector<int> a{1,2,3};
std::map<int,int> b;
b[0] = 1;
b[2] = 3;
b[4] = 5;
auto&& iter1 = my_find(a,2);
std::cout << ( iter1 == a.end() ? "not found" : "found" ) << std::endl;
std::cout << std::endl;
auto&& iter2 = my_find(b,2);
std::cout << ( iter2 == b.end() ? "not found" : "found" ) << std::endl;
return 0;
}
template < typename T >
auto f(T&& arg)->decltype(arg.f())
{
std::cout << "Has f()." << std::endl;
}
template < typename T >
auto f(T&& arg)->void
{
std::cout << "Hasn't f()." << std::endl;
}
struct hoge{};
f( hoge{} ) ; // OK! Hasn't f()
struct piyo{
void f(){}
};
f( piyo{} ) ; // オーバーロードの解決が曖昧!
extern std::nullptr_t enabler;
template < typename T >
struct has_func
{
private :
template < typename U >
static auto check(U x) -> decltype( x.f(), std::true_type{} ) ;
static std::false_type check(...) ;
public :
static bool const value = decltype( check( std::declval<T>() ) )::value ;
} ;
template < typename T >
auto f( T&& arg )->decltype(arg.f())
{
std::cout << "The class has f()." << std::endl;
}
template < typename T, std::enable_if_t<!has_func<T>::value>*& = enabler >
auto f( T&& )->void
{
std::cout << "The class hasn't f()." << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment