Skip to content

Instantly share code, notes, and snippets.

@loliGothicK
Last active August 2, 2016 07:41
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/c4fc18cf1ed4c08d33df to your computer and use it in GitHub Desktop.
Save loliGothicK/c4fc18cf1ed4c08d33df to your computer and use it in GitHub Desktop.
C++関数テンプレートと半順序とオーバーロード ref: http://qiita.com/_EnumHack/items/cd904d383588ddb2189f
template < typename T >
T max(T a, T b) ;
max(1,2); // T is int
max(1.0, 3.0); // T is double
template < typename T >
void f(T) ;
f({1,2,3}); // error!
template < typename L, typename R >
auto f(L&& a, R&& b)
{
return a + b ;
}
template < typename L, typename R >
decltype(auto) f(L&& a, R&& b)
{
return a + b ;
}
template < typename L, typename R >
decltype(auto) f(L&& a, R&& b)
{
return (a + b) ;
}
template < typename L, typename R >
auto f(L&& a, R&& b)->decltype(a + b)
{
return a + b;
}
template <typename T, std::enable_if_t<pred>*& =nullptr_t>
void f(T t){}
template <typename T>
std::enable_if_t<pred,ReturnType> f(T t){}
template <typename T>
void f(T t,std::enable_if_t<pred>*=nullptr){}
#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;
}
double max(double a, double b); // #1
int max(int a, int b); // #2
max(1.0, 2.0); // calls #1
max(1,2) // calls #2
template < typename T >
T f(T a, T b)
{
return a + b ;
}
template < >
int f<int>(int a, int b)
{
return a * b ;
}
template < typename T >
T f(T a, T b)
{
return a + b ;
}
template < >
int f<int>(int a, int b) = delete ;
template < typename L, typename R >
void f(L lhs, R rhs) ;
template < typename L >
void f<L,int>(L lhs, int rhs) ; // Error !
template < >
void f<int,int>(int lhs, int rhs) ; // OK !
template < typename T >
void f(T* p) ; // Tのポインタのみを引数に取る
template < typename T >
void f( typename hoge<T>::type ){} // non-deduced contexts
template< std::size_t N >
void foo( int(&)[2*N] ){} // error
template< std::size_t N >
void bar( int(&)[N] ){} // OK
template < typename T >
void f( T = 0 ) ;
f() // error!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment