Fungsi <functional>
Fungsi-fungsi ini tidak digunakan lagi di C++11 dan dihapus di C++17:
bind1st
bind2nd
mem_fun
mem_fun_ref
ptr_fun
Fungsi-fungsi ini tidak digunakan lagi dalam C++17:
bind
Mengikat argumen ke objek yang dapat dipanggil.
template <class FT, class T1, class T2, ..., class TN>
unspecified bind(FT fn, T1 t1, T2 t2, ..., TN tN);
template <class RTy, class FT, class T1, class T2, ..., class TN>
unspecified bind(FT fn, T1 t1, T2 t2, ..., TN tN);
Parameter
FT
Jenis objek yang akan dipanggil. Misalnya, jenis fungsi, objek fungsi, penunjuk/referensi fungsi, atau penunjuk fungsi anggota.
RTy
Jenis pengembalian. Ketika ditentukan, itu akan menjadi jenis pengembalian panggilan terikat. Jika tidak, jenis pengembalian adalah jenis pengembalian dari FT
.
TN
Jenis argumen panggilan Nth.
fn
Objek yang akan dipanggil.
tN
Argumen panggilan Nth.
Keterangan
Jenis FT, T1, T2, ..., TN
harus copy-constructible, dan INVOKE(fn, t1, ..., tN)
harus merupakan ekspresi yang valid untuk beberapa nilai w1, w2, ..., wN
.
Fungsi templat pertama mengembalikan pembungkus g
panggilan penerusan dengan jenis hasil yang lemah. Efeknya g(u1, u2, ..., uM)
adalah INVOKE(f, v1, v2, ..., vN,
invoke_result<FT cv (V1, V2, ..., VN)>::type)
, di mana cv
adalah kualifikasi g
cv dan nilai dan jenis argumen v1, v2, ..., vN
terikat ditentukan seperti yang ditentukan di bawah ini. Anda menggunakannya untuk mengikat argumen ke objek yang dapat dipanggil untuk membuat objek yang dapat dipanggil dengan daftar argumen yang disesuaikan.
Fungsi templat kedua mengembalikan pembungkus g
panggilan penerusan dengan jenis result_type
berlapis yang merupakan sinonim untuk RTy
. Efeknya g(u1, u2, ..., uM)
adalah INVOKE(f, v1, v2, ..., vN, RTy)
, di mana cv
adalah kualifikasi g
cv dan nilai dan jenis argumen v1, v2, ..., vN
terikat ditentukan seperti yang ditentukan di bawah ini. Anda menggunakannya untuk mengikat argumen ke objek yang dapat dipanggil untuk membuat objek yang dapat dipanggil dengan daftar argumen yang disesuaikan dan dengan jenis pengembalian yang ditentukan.
Nilai argumen v1, v2, ..., vN
terikat dan jenis V1, V2, ..., VN
yang sesuai bergantung pada jenis argumen ti
jenis Ti
yang sesuai dalam panggilan ke bind
dan kualifikasi cv
cv dari pembungkus g
panggilan sebagai berikut:
Jika ti
berjenis reference_wrapper<T>
argumen vi
adalah ti.get()
dan jenisnya Vi
adalah T&
;
Jika nilai adalah argumen adalah dan jenisnya Vi
adalah result_of<Ti
(U1&, U2&, ..., UN&>::type
cv
;ti(u1, u2, ..., uM)
vi
true
std::is_bind_expression<Ti>::value
Jika nilai j
std::is_placeholder<Ti>::value
bukan nol argumen vi
adalah uj
dan jenisnya Vi
adalah Uj&
;
Jika tidak, argumen vi
adalah dan jenisnya Vi
adalah Ti
cv
&
.ti
Misalnya, dengan fungsi f(int, int)
, ekspresi bind(f, _1, 0)
mengembalikan pembungkus cw
panggilan penerusan sehingga cw(x)
memanggil f(x, 0)
. Ekspresi bind(f, 0, _1)
mengembalikan pembungkus cw
panggilan penerusan sehingga cw(x)
memanggil f(0, x)
.
Jumlah argumen dalam panggilan ke bind
dan argumen fn
harus sama dengan jumlah argumen yang dapat diteruskan ke objek fn
yang dapat dipanggil . Misalnya, bind(cos, 1.0)
benar, dan keduanya bind(cos)
dan bind(cos, _1, 0.0)
salah.
Jumlah argumen dalam panggilan fungsi ke pembungkus panggilan yang dikembalikan oleh bind
harus setidaknya sebesar nilai is_placeholder<PH>::value
bernomor tertinggi untuk semua argumen tempat penampung dalam panggilan ke bind
. Misalnya, bind(cos, _2)(0.0, 1.0)
sudah benar (dan mengembalikan cos(1.0)
), dan bind(cos, _2)(0.0)
salah.
Contoh
// std__functional__bind.cpp
// compile with: /EHsc
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std::placeholders;
void square(double x)
{
std::cout << x << "^2 == " << x * x << std::endl;
}
void product(double x, double y)
{
std::cout << x << "*" << y << " == " << x * y << std::endl;
}
int main()
{
double arg[] = { 1, 2, 3 };
std::for_each(&arg[0], arg + 3, square);
std::cout << std::endl;
std::for_each(&arg[0], arg + 3, std::bind(product, _1, 2));
std::cout << std::endl;
std::for_each(&arg[0], arg + 3, std::bind(square, _1));
return (0);
}
1^2 == 1
2^2 == 4
3^2 == 9
1*2 == 2
2*2 == 4
3*2 == 6
1^2 == 1
2^2 == 4
3^2 == 9
bind1st
Fungsi templat pembantu yang membuat adaptor untuk mengonversi objek fungsi biner menjadi objek fungsi unary. Ini mengikat argumen pertama dari fungsi biner ke nilai tertentu. Tidak digunakan lagi di C++11, dihapus di C++17.
template <class Operation, class Type>
binder1st <Operation> bind1st (const Operation& func, const Type& left);
Parameter
func
Objek fungsi biner yang akan dikonversi ke objek fungsi unary.
left
Nilai di mana argumen pertama objek fungsi biner akan terikat.
Tampilkan Nilai
Objek fungsi unary yang dihasilkan dari mengikat argumen pertama objek fungsi biner ke nilai left
.
Keterangan
Pengikat fungsi adalah semacam adaptor fungsi. Karena mengembalikan objek fungsi, objek tersebut dapat digunakan dalam jenis komposisi fungsi tertentu untuk membangun ekspresi yang lebih rumit dan kuat.
Jika func
adalah objek jenis Operation
dan c
merupakan konstanta, maka bind1st( func, c )
sama binder1st
dengan konstruktor binder1st<Operation>(func, c)
kelas , dan lebih nyaman digunakan.
Contoh
// functional_bind1st.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;
// Creation of a user-defined function object
// that inherits from the unary_function base class
class greaterthan5: unary_function<int, bool>
{
public:
result_type operator()(argument_type i)
{
return (result_type)(i > 5);
}
};
int main()
{
vector<int> v1;
vector<int>::iterator Iter;
int i;
for (i = 0; i <= 5; i++)
{
v1.push_back(5 * i);
}
cout << "The vector v1 = ( " ;
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << *Iter << " ";
cout << ")" << endl;
// Count the number of integers > 10 in the vector
vector<int>::iterator::difference_type result1a;
result1a = count_if(v1.begin(), v1.end(), bind1st(less<int>(), 10));
cout << "The number of elements in v1 greater than 10 is: "
<< result1a << "." << endl;
// Compare: counting the number of integers > 5 in the vector
// with a user defined function object
vector<int>::iterator::difference_type result1b;
result1b = count_if(v1.begin(), v1.end(), greaterthan5());
cout << "The number of elements in v1 greater than 5 is: "
<< result1b << "." << endl;
// Count the number of integers < 10 in the vector
vector<int>::iterator::difference_type result2;
result2 = count_if(v1.begin(), v1.end(), bind2nd(less<int>(), 10));
cout << "The number of elements in v1 less than 10 is: "
<< result2 << "." << endl;
}
The vector v1 = ( 0 5 10 15 20 25 )
The number of elements in v1 greater than 10 is: 3.
The number of elements in v1 greater than 5 is: 4.
The number of elements in v1 less than 10 is: 2.
bind2nd
Fungsi templat pembantu yang membuat adaptor untuk mengonversi objek fungsi biner menjadi objek fungsi unary. Ini mengikat argumen kedua dari fungsi biner ke nilai tertentu. Tidak digunakan lagi di C++11, dihapus di C++17.
template <class Operation, class Type>
binder2nd <Operation> bind2nd(const Operation& func, const Type& right);
Parameter
func
Objek fungsi biner yang akan dikonversi ke objek fungsi unary.
right
Nilai di mana argumen kedua objek fungsi biner akan terikat.
Tampilkan Nilai
Hasil objek fungsi unary dari pengikatan argumen kedua objek fungsi biner ke right
.
Keterangan
Pengikat fungsi adalah semacam adaptor fungsi. Karena mengembalikan objek fungsi, objek tersebut dapat digunakan dalam jenis komposisi fungsi tertentu untuk membangun ekspresi yang lebih rumit dan kuat.
Jika func
adalah objek jenis Operation
dan c
merupakan konstanta, maka bind2nd(func, c)
sama binder2nd
dengan konstruktor binder2nd<Operation>(func, c)
kelas , dan lebih nyaman digunakan.
Contoh
// functional_bind2nd.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;
// Creation of a user-defined function object
// that inherits from the unary_function base class
class greaterthan15: unary_function<int, bool>
{
public:
result_type operator()(argument_type i)
{
return (result_type)(i > 15);
}
};
int main()
{
vector<int> v1;
vector<int>::iterator Iter;
int i;
for (i = 0; i <= 5; i++)
{
v1.push_back(5 * i);
}
cout << "The vector v1 = ( ";
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << *Iter << " ";
cout << ")" << endl;
// Count the number of integers > 10 in the vector
vector<int>::iterator::difference_type result1a;
result1a = count_if(v1.begin(), v1.end(), bind2nd(greater<int>(), 10));
cout << "The number of elements in v1 greater than 10 is: "
<< result1a << "." << endl;
// Compare counting the number of integers > 15 in the vector
// with a user-defined function object
vector<int>::iterator::difference_type result1b;
result1b = count_if(v1.begin(), v1.end(), greaterthan15());
cout << "The number of elements in v1 greater than 15 is: "
<< result1b << "." << endl;
// Count the number of integers < 10 in the vector
vector<int>::iterator::difference_type result2;
result2 = count_if(v1.begin(), v1.end(), bind1st(greater<int>(), 10));
cout << "The number of elements in v1 less than 10 is: "
<< result2 << "." << endl;
}
The vector v1 = ( 0 5 10 15 20 25 )
The number of elements in v1 greater than 10 is: 3.
The number of elements in v1 greater than 15 is: 2.
The number of elements in v1 less than 10 is: 2.
bit_and
Objek fungsi yang telah ditentukan sebelumnya yang melakukan operasi BITWISE AND (biner operator&
) pada argumennya.
template <class Type = void>
struct bit_and : public binary_function<Type, Type, Type
{
Type operator()(
const Type& Left,
const Type& Right) const;
};
// specialized transparent functor for operator&
template <>
struct bit_and<void>
{
template <class T, class U>
auto operator()(T&& Left, U&& Right) const ->
decltype(std::forward<T>(Left) & std::forward<U>(Right));
};
Parameter
Type
, , T
U
Jenis apa pun yang mendukung operator&
yang mengambil operan dari jenis yang ditentukan atau disimpulkan.
Left
Operan kiri operasi BITWISE AND. Templat yang tidak dispesialisasi mengambil argumen referensi lvalue jenis Type
. Templat khusus melakukan penerusan sempurna dari argumen referensi lvalue dan rvalue dari jenis T
yang disimpulkan .
Right
Operan kanan operasi BITWISE AND. Templat yang tidak dispesialisasi mengambil argumen referensi lvalue jenis Type
. Templat khusus melakukan penerusan sempurna dari argumen referensi lvalue dan rvalue dari jenis U
yang disimpulkan .
Tampilkan Nilai
Hasil dari Left & Right
. Templat khusus melakukan penerusan hasil yang sempurna, yang memiliki jenis yang dikembalikan oleh operator&
.
Keterangan
Functor bit_and
dibatasi untuk jenis integral untuk jenis data dasar, atau untuk jenis yang ditentukan pengguna yang mengimplementasikan biner operator&
.
bit_not
Objek fungsi yang telah ditentukan sebelumnya yang melakukan operasi pelengkap bitwise (NOT) (tidak biasa operator~
) pada argumennya. Ditambahkan dalam C++14.
template <class Type = void>
struct bit_not : public unary_function<Type, Type>
{
Type operator()(const Type& Right) const;
};
// specialized transparent functor for operator~
template <>
struct bit_not<void>
{
template <class Type>
auto operator()(Type&& Right) const -> decltype(~std::forward<Type>(Right));
};
Parameter
Type
Jenis yang mendukung unary operator~
.
Right
Operan operasi pelengkap bitwise. Templat yang tidak dispesialisasi mengambil argumen referensi lvalue jenis Type
. Templat khusus melakukan penerusan sempurna dari argumen referensi lvalue atau rvalue dari jenis Type
yang disimpulkan .
Tampilkan Nilai
Hasil dari ~ Right
. Templat khusus melakukan penerusan hasil yang sempurna, yang memiliki jenis yang dikembalikan oleh operator~
.
Keterangan
Functor bit_not
dibatasi untuk jenis integral untuk jenis data dasar, atau untuk jenis yang ditentukan pengguna yang mengimplementasikan biner operator~
.
bit_or
Objek fungsi yang telah ditentukan sebelumnya yang melakukan operasi BITWISE OR (operator|
) pada argumennya.
template <class Type = void>
struct bit_or : public binary_function<Type, Type, Type>
{
Type operator()(
const Type& Left,
const Type& Right) const;
};
// specialized transparent functor for operator|
template <>
struct bit_or<void>
{
template <class T, class U>
auto operator()(T&& Left, U&& Right) const
-> decltype(std::forward<T>(Left) | std::forward<U>(Right));
};
Parameter
Type
, , T
U
Jenis apa pun yang mendukung operator|
yang mengambil operan dari jenis yang ditentukan atau disimpulkan.
Left
Operan kiri operasi BITWISE OR. Templat yang tidak dispesialisasi mengambil argumen referensi lvalue jenis Type
. Templat khusus melakukan penerusan sempurna dari argumen referensi lvalue dan rvalue dari jenis T
yang disimpulkan .
Right
Operan kanan operasi BITWISE OR. Templat yang tidak dispesialisasi mengambil argumen referensi lvalue jenis Type
. Templat khusus melakukan penerusan sempurna dari argumen referensi lvalue dan rvalue dari jenis U
yang disimpulkan .
Tampilkan Nilai
Hasil dari Left | Right
. Templat khusus melakukan penerusan hasil yang sempurna, yang memiliki jenis yang dikembalikan oleh operator|
.
Keterangan
Functor bit_or
dibatasi untuk jenis integral untuk jenis data dasar, atau untuk jenis yang ditentukan pengguna yang mengimplementasikan operator|
.
bit_xor
Objek fungsi yang telah ditentukan sebelumnya yang melakukan operasi XOR bitwise (biner operator^
) pada argumennya.
template <class Type = void>
struct bit_xor : public binary_function<Type, Type, Type>
{
Type operator()(
const Type& Left,
const Type& Right) const;
};
// specialized transparent functor for operator^
template <>
struct bit_xor<void>
{
template <class T, class U>
auto operator()(T&& Left, U&& Right) const
-> decltype(std::forward<T>(Left) ^ std::forward<U>(Right));
};
Parameter
Type
, , T
U
Jenis apa pun yang mendukung operator^
yang mengambil operan dari jenis yang ditentukan atau disimpulkan.
Left
Operan kiri operasi XOR bitwise. Templat yang tidak dispesialisasi mengambil argumen referensi lvalue jenis Type
. Templat khusus melakukan penerusan sempurna dari argumen referensi lvalue dan rvalue dari jenis T
yang disimpulkan .
Right
Operan kanan operasi XOR bitwise. Templat yang tidak dispesialisasi mengambil argumen referensi lvalue jenis Type
. Templat khusus melakukan penerusan sempurna dari argumen referensi lvalue dan rvalue dari jenis U
yang disimpulkan .
Tampilkan Nilai
Hasil dari Left ^ Right
. Templat khusus melakukan penerusan hasil yang sempurna, yang memiliki jenis yang dikembalikan oleh operator^
.
Keterangan
Functor bit_xor
dibatasi untuk jenis integral untuk jenis data dasar, atau untuk jenis yang ditentukan pengguna yang mengimplementasikan biner operator^
.
cref
Membuat const reference_wrapper
dari argumen.
template <class Ty>
reference_wrapper<const Ty> cref(const Ty& arg);
template <class Ty>
reference_wrapper<const Ty> cref(const reference_wrapper<Ty>& arg);
Parameter
Ty
Jenis argumen yang akan dibungkus.
arg
Argumen untuk dibungkus.
Keterangan
Fungsi pertama mengembalikan reference_wrapper<const Ty>(arg.get())
. Anda menggunakannya untuk membungkus referensi const. Fungsi kedua mengembalikan reference_wrapper<const Ty>(arg)
. Anda menggunakannya untuk membungkus ulang referensi yang dibungkus sebagai referensi const.
Contoh
// std__functional__cref.cpp
// compile with: /EHsc
#include <functional>
#include <iostream>
int neg(int val)
{
return (-val);
}
int main()
{
int i = 1;
std::cout << "i = " << i << std::endl;
std::cout << "cref(i) = " << std::cref(i) << std::endl;
std::cout << "cref(neg)(i) = "
<< std::cref(&neg)(i) << std::endl;
return (0);
}
i = 1
cref(i) = 1
cref(neg)(i) = -1
Memohon
Memanggil objek yang dapat dipanggil dengan argumen yang diberikan. Ditambahkan di C++17.
template <class Callable, class... Args>
invoke_result_t<Callable, Args...>
invoke(Callable&& fn, Args&&... args) noexcept(/* specification */);
Parameter
Callable
Jenis objek yang akan dipanggil.
Args
Jenis argumen panggilan.
fn
Objek yang akan dipanggil.
args
Argumen panggilan.
specification
Spesifikasi std::is_nothrow_invocable_v<Callable, Args>)
.noexcept
Keterangan
Memanggil objek fn
yang dapat dipanggil menggunakan parameter args
. Secara efektif, INVOKE(std::forward<Callable>(fn), std::forward<Args>(args)...)
, di mana fungsi INVOKE(f, t1, t2, ..., tN)
pseudo berarti salah satu hal berikut:
(t1.*f)(t2, ..., tN)
ketikaf
adalah fungsi penunjuk ke anggota kelasT
dant1
merupakan objek jenisT
atau referensi ke objek jenisT
atau referensi ke objek jenis yang berasal dariT
. Artinya, kapanstd::is_base_of<T, std::decay_t<decltype(t1)>>::value
itu benar.(t1.get().*f)(t2, ..., tN)
kapanf
adalah fungsi penunjuk ke anggota kelasT
danstd::decay_t<decltype(t1)>
merupakan spesialisasi daristd::reference_wrapper
.((*t1).*f)(t2, ..., tN)
kapanf
adalah fungsi penunjuk ke anggota kelasT
dant1
bukan salah satu jenis sebelumnya.t1.*f
ketika N == 1 danf
merupakan penunjuk ke data anggota kelasT
dant1
merupakan objek jenisT
atau referensi ke objek jenisT
atau referensi ke objek jenis yang berasal dariT
. Artinya, kapanstd::is_base_of<T, std::decay_t<decltype(t1)>>::value
itu benar.t1.get().*f
ketika N == 1 danf
merupakan penunjuk ke data anggota kelasT
danstd::decay_t<decltype(t1)>
merupakan spesialisasi daristd::reference_wrapper
.(*t1).*f
ketika N == 1 danf
merupakan penunjuk ke data anggota kelasT
dant1
bukan salah satu jenis sebelumnya.f(t1, t2, ..., tN)
dalam semua kasus lainnya.
Untuk informasi tentang jenis hasil objek yang dapat dipanggil, lihat invoke_result. Untuk predikat tentang jenis yang dapat dipanggil, lihat kelas is_invocable, is_invocable_r, is_nothrow_invocable, is_nothrow_invocable_r.
Contoh
// functional_invoke.cpp
// compile using: cl /EHsc /std:c++17 functional_invoke.cpp
#include <functional>
#include <iostream>
struct Demo
{
int n_;
Demo(int const n) : n_{n} {}
void operator()( int const i, int const j ) const
{
std::cout << "Demo operator( " << i << ", "
<< j << " ) is " << i * j << "\n";
}
void difference( int const i ) const
{
std::cout << "Demo.difference( " << i << " ) is "
<< n_ - i << "\n";
}
};
void divisible_by_3(int const i)
{
std::cout << i << ( i % 3 == 0 ? " is" : " isn't" )
<< " divisible by 3.\n";
}
int main()
{
Demo d{ 42 };
Demo * pd{ &d };
auto pmf = &Demo::difference;
auto pmd = &Demo::n_;
// Invoke a function object, like calling d( 3, -7 )
std::invoke( d, 3, -7 );
// Invoke a member function, like calling
// d.difference( 29 ) or (d.*pmf)( 29 )
std::invoke( &Demo::difference, d, 29 );
std::invoke( pmf, pd, 13 );
// Invoke a data member, like access to d.n_ or d.*pmd
std::cout << "d.n_: " << std::invoke( &Demo::n_, d ) << "\n";
std::cout << "pd->n_: " << std::invoke( pmd, pd ) << "\n";
// Invoke a stand-alone (free) function
std::invoke( divisible_by_3, 42 );
// Invoke a lambda
auto divisible_by_7 = []( int const i )
{
std::cout << i << ( i % 7 == 0 ? " is" : " isn't" )
<< " divisible by 7.\n";
};
std::invoke( divisible_by_7, 42 );
}
Demo operator( 3, -7 ) is -21
Demo.difference( 29 ) is 13
Demo.difference( 13 ) is 29
d.n_: 42
pd->n_: 42
42 is divisible by 3.
42 is divisible by 7.
mem_fn
Menghasilkan pembungkus panggilan sederhana.
template <class RTy, class Ty>
unspecified mem_fn(RTy Ty::*pm);
Parameter
RTy
Jenis pengembalian fungsi yang dibungkus.
Ty
Jenis penunjuk fungsi anggota.
Keterangan
Fungsi templat mengembalikan pembungkus cw
panggilan sederhana , dengan jenis hasil yang lemah, sehingga ekspresinya cw(t, a2, ..., aN)
sama dengan INVOKE(pm, t, a2, ..., aN)
. Ini tidak melemparkan pengecualian apa pun.
Pembungkus panggilan yang dikembalikan berasal dari std::unary_function<cv Ty*, RTy>
(dan mendefinisikan jenis result_type
berlapis sebagai sinonim untuk RTy
dan jenis argument_type
berlapis sebagai sinonim untuk cv Ty*
) hanya jika jenis Ty
adalah penunjuk ke fungsi anggota dengan cv-qualifier cv
yang tidak mengambil argumen.
Pembungkus panggilan yang dikembalikan berasal dari std::binary_function<cv Ty*, T2, RTy>
(dan menentukan jenis result_type
berlapis sebagai sinonim untuk RTy
, jenis first argument_type
berlapis sebagai sinonim untuk cv Ty*
, dan jenis second argument_type
berlapis sebagai sinonim untuk T2
) hanya jika jenisnya Ty
adalah penunjuk ke fungsi anggota dengan cv-qualifier cv
yang mengambil satu argumen, jenis T2
.
Contoh
// std__functional__mem_fn.cpp
// compile with: /EHsc
#include <functional>
#include <iostream>
class Funs
{
public:
void square(double x)
{
std::cout << x << "^2 == " << x * x << std::endl;
}
void product(double x, double y)
{
std::cout << x << "*" << y << " == " << x * y << std::endl;
}
};
int main()
{
Funs funs;
std::mem_fn(&Funs::square)(funs, 3.0);
std::mem_fn(&Funs::product)(funs, 3.0, 2.0);
return (0);
}
3^2 == 9
3*2 == 6
mem_fun
Fungsi templat pembantu yang digunakan untuk membangun adaptor objek fungsi untuk fungsi anggota saat diinisialisasi dengan argumen penunjuk. Tidak digunakan lagi di C++11 untuk mem_fn
dan bind
, dan dihapus di C++17.
template <class Result, class Type>
mem_fun_t<Result, Type> mem_fun (Result(Type::* pMem)());
template <class Result, class Type, class Arg>
mem_fun1_t<Result, Type, Arg> mem_fun(Result (Type::* pMem)(Arg));
template <class Result, class Type>
const_mem_fun_t<Result, Type> mem_fun(Result (Type::* pMem)() const);
template <class Result, class Type, class Arg>
const_mem_fun1_t<Result, Type, Arg> mem_fun(Result (Type::* pMem)(Arg) const);
Parameter
pMem
Penunjuk ke fungsi anggota kelas Type
yang akan dikonversi ke objek fungsi.
Tampilkan Nilai
Objek const
fungsi atau non-const dari jenis mem_fun_t
atau mem_fun1_t
.
Contoh
// functional_mem_fun.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;
class StoreVals
{
int val;
public:
StoreVals() { val = 0; }
StoreVals(int j) { val = j; }
bool display() { cout << val << " "; return true; }
int squareval() { val *= val; return val; }
int lessconst(int k) {val -= k; return val; }
};
int main( )
{
vector<StoreVals *> v1;
StoreVals sv1(5);
v1.push_back(&sv1);
StoreVals sv2(10);
v1.push_back(&sv2);
StoreVals sv3(15);
v1.push_back(&sv3);
StoreVals sv4(20);
v1.push_back(&sv4);
StoreVals sv5(25);
v1.push_back(&sv5);
cout << "The original values stored are: " ;
for_each(v1.begin(), v1.end(), mem_fun<bool, StoreVals>(&StoreVals::display));
cout << endl;
// Use of mem_fun calling member function through a pointer
// square each value in the vector using squareval ()
for_each(v1.begin(), v1.end(), mem_fun<int, StoreVals>(&StoreVals::squareval));
cout << "The squared values are: " ;
for_each(v1.begin(), v1.end(), mem_fun<bool, StoreVals>(&StoreVals::display));
cout << endl;
// Use of mem_fun1 calling member function through a pointer
// subtract 5 from each value in the vector using lessconst ()
for_each(v1.begin(), v1.end(),
bind2nd (mem_fun1<int, StoreVals,int>(&StoreVals::lessconst), 5));
cout << "The squared values less 5 are: " ;
for_each(v1.begin(), v1.end(), mem_fun<bool, StoreVals>(&StoreVals::display));
cout << endl;
}
mem_fun_ref
Fungsi templat pembantu yang digunakan untuk membangun adaptor objek fungsi untuk fungsi anggota saat diinisialisasi dengan menggunakan argumen referensi. Tidak digunakan lagi di C++11, dihapus di C++17.
template <class Result, class Type>
mem_fun_ref_t<Result, Type> mem_fun_ref(Result (Type::* pMem)());
template <class Result, class Type, class Arg>
mem_fun1_ref_t<Result, Type, Arg> mem_fun_ref(Result (Type::* pMem)(Arg));
template <class Result, class Type>
const_mem_fun_ref_t<Result, Type> mem_fun_ref(Result Type::* pMem)() const);
template <class Result, class Type, class Arg>
const_mem_fun1_ref_t<Result, Type, Arg> mem_fun_ref(Result (T::* pMem)(Arg) const);
Parameter
pMem
Penunjuk ke fungsi anggota kelas Type
yang akan dikonversi ke objek fungsi.
Tampilkan Nilai
Objek const
fungsi atau non_const
jenis mem_fun_ref_t
atau mem_fun1_ref_t
.
Contoh
// functional_mem_fun_ref.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;
class NumVals
{
int val;
public:
NumVals ( ) { val = 0; }
NumVals ( int j ) { val = j; }
bool display ( ) { cout << val << " "; return true; }
bool isEven ( ) { return ( bool ) !( val %2 ); }
bool isPrime( )
{
if (val < 2) { return true; }
for (int i = 2; i <= val / i; ++i)
{
if (val % i == 0) { return false; }
}
return true;
}
};
int main( )
{
vector <NumVals> v1 ( 13 ), v2 ( 13 );
vector <NumVals>::iterator v1_Iter, v2_Iter;
int i, k;
for ( i = 0; i < 13; i++ ) v1 [ i ] = NumVals ( i+1 );
for ( k = 0; k < 13; k++ ) v2 [ k ] = NumVals ( k+1 );
cout << "The original values stored in v1 are: " ;
for_each( v1.begin( ), v1.end( ),
mem_fun_ref ( &NumVals::display ) );
cout << endl;
// Use of mem_fun_ref calling member function through a reference
// remove the primes in the vector using isPrime ( )
v1_Iter = remove_if ( v1.begin( ), v1.end( ),
mem_fun_ref ( &NumVals::isPrime ) );
cout << "With the primes removed, the remaining values in v1 are: " ;
for_each( v1.begin( ), v1_Iter,
mem_fun_ref ( &NumVals::display ) );
cout << endl;
cout << "The original values stored in v2 are: " ;
for_each( v2.begin( ), v2.end( ),
mem_fun_ref ( &NumVals::display ) );
cout << endl;
// Use of mem_fun_ref calling member function through a reference
// remove the even numbers in the vector v2 using isEven ( )
v2_Iter = remove_if ( v2.begin( ), v2.end( ),
mem_fun_ref ( &NumVals::isEven ) );
cout << "With the even numbers removed, the remaining values are: " ;
for_each( v2.begin( ), v2_Iter,
mem_fun_ref ( &NumVals::display ) );
cout << endl;
}
The original values stored in v1 are: 1 2 3 4 5 6 7 8 9 10 11 12 13
With the primes removed, the remaining values in v1 are: 4 6 8 9 10 12
The original values stored in v2 are: 1 2 3 4 5 6 7 8 9 10 11 12 13
With the even numbers removed, the remaining values are: 1 3 5 7 9 11 13
not1
Mengembalikan pelengkap predikat unary. Tidak digunakan lagi untuk not_fn
di C++17.
template <class UnaryPredicate>
unary_negate<UnaryPredicate> not1(const UnaryPredicate& predicate);
Parameter
predicate
Predikat unary untuk dinegasikan.
Tampilkan Nilai
Predikat unary yang merupakan negasi dari predikat unary yang dimodifikasi.
Keterangan
unary_negate
Jika dibangun dari predikat predicate(x)
unary , maka akan mengembalikan !predicate(x)
.
Contoh
// functional_not1.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
vector<int> v1;
vector<int>::iterator Iter;
int i;
for (i = 0; i <= 7; i++)
{
v1.push_back(5 * i);
}
cout << "The vector v1 = ( ";
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << *Iter << " ";
cout << ")" << endl;
vector<int>::iterator::difference_type result1;
// Count the elements greater than 10
result1 = count_if(v1.begin(), v1.end(), bind2nd(greater<int>(), 10));
cout << "The number of elements in v1 greater than 10 is: "
<< result1 << "." << endl;
vector<int>::iterator::difference_type result2;
// Use the negator to count the elements less than or equal to 10
result2 = count_if(v1.begin(), v1.end(),
not1(bind2nd(greater<int>(), 10)));
cout << "The number of elements in v1 not greater than 10 is: "
<< result2 << "." << endl;
}
The vector v1 = ( 0 5 10 15 20 25 30 35 )
The number of elements in v1 greater than 10 is: 5.
The number of elements in v1 not greater than 10 is: 3.
not2
Mengembalikan pelengkap predikat biner. Tidak digunakan lagi untuk not_fn
di C++17.
template <class BinaryPredicate>
binary_negate<BinaryPredicate> not2(const BinaryPredicate& func);
Parameter
func
Predikat biner yang akan dinegasikan.
Tampilkan Nilai
Predikat biner yang merupakan negasi dari predikat biner yang dimodifikasi.
Keterangan
binary_negate
Jika dibangun dari predikat binary_predicate(x, y)
biner, maka akan mengembalikan !binary_predicate(x, y)
.
Contoh
// functional_not2.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <functional>
#include <cstdlib>
#include <iostream>
int main( )
{
using namespace std;
vector <int> v1;
vector <int>::iterator Iter1;
int i;
v1.push_back( 6262 );
v1.push_back( 6262 );
for ( i = 0 ; i < 5 ; i++ )
{
v1.push_back( rand( ) );
}
cout << "Original vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
// To sort in ascending order,
// use default binary predicate less<int>( )
sort( v1.begin( ), v1.end( ) );
cout << "Sorted vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
// To sort in descending order,
// use the binary_negate helper function not2
sort( v1.begin( ), v1.end( ), not2(less<int>( ) ) );
cout << "Resorted vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
}
Original vector v1 = ( 6262 6262 41 18467 6334 26500 19169 )
Sorted vector v1 = ( 41 6262 6262 6334 18467 19169 26500 )
Resorted vector v1 = ( 26500 19169 18467 6334 6262 6262 41 )
not_fn
not_fn
Templat fungsi mengambil objek yang dapat dipanggil dan mengembalikan objek yang dapat dipanggil. Ketika objek yang dapat dipanggil yang dikembalikan kemudian dipanggil dengan beberapa argumen, objek tersebut meneruskannya ke objek asli yang dapat dipanggil, dan secara logis meniadakan hasilnya. Ini mempertahankan kualifikasi const dan perilaku kategori nilai dari objek yang dapat dipanggil yang dibungkus. not_fn
baru di C++17, dan menggantikan yang tidak digunakan std::not1
lagi, , std::not2
std::unary_negate
, dan std::binary_negate
.
template <class Callable>
/* unspecified */ not_fn(Callable&& func);
Parameter
func
Objek yang dapat dipanggil digunakan untuk membangun pembungkus panggilan penerusan.
Keterangan
Fungsi templat mengembalikan pembungkus panggilan seperti return call_wrapper(std::forward<Callable>(func))
, berdasarkan kelas khusus eksposisi ini:
class call_wrapper
{
using FD = decay_t<Callable>;
explicit call_wrapper(Callable&& func);
public:
call_wrapper(call_wrapper&&) = default;
call_wrapper(call_wrapper const&) = default;
template<class... Args>
auto operator()(Args&&...) & -> decltype(!declval<invoke_result_t<FD&(Args...)>>());
template<class... Args>
auto operator()(Args&&...) const& -> decltype(!declval<invoke_result_t<FD const&(Args...)>>());
template<class... Args>
auto operator()(Args&&...) && -> decltype(!declval<invoke_result_t<FD(Args...)>>());
template<class... Args>
auto operator()(Args&&...) const&& -> decltype(!declval<invoke_result_t<FD const(Args...)>>());
private:
FD fd;
};
Konstruktor eksplisit pada objek func
yang dapat dipanggil memerlukan jenis std::decay_t<Callable>
untuk memenuhi persyaratan MoveConstructible
, dan is_constructible_v<FD, Callable>
harus benar. Ini menginisialisasi objek fd
yang dapat dipanggil yang dibungkus dari std::forward<Callable>(func)
, dan melemparkan pengecualian apa pun yang dilemparkan oleh konstruksi fd
.
Pembungkus mengekspos operator panggilan yang dibedakan oleh kategori referensi lvalue atau rvalue dan kualifikasi konstan seperti yang ditunjukkan di sini:
template<class... Args> auto operator()(Args&&... args) & -> decltype(!declval<invoke_result_t<FD&(Args...)>>());
template<class... Args> auto operator()(Args&&... args) const& -> decltype(!declval<invoke_result_t<FD const&(Args...)>>());
template<class... Args> auto operator()(Args&&... args) && -> decltype(!declval<invoke_result_t<FD(Args...)>>());
template<class... Args> auto operator()(Args&&... args) const&& -> decltype(!declval<invoke_result_t<FD const(Args...)>>());
Dua yang pertama sama dengan return !std::invoke(fd, std::forward<Args>(args)...)
. Dua yang kedua sama dengan return !std::invoke(std::move(fd), std::forward<Args>(args)...)
.
Contoh
// functional_not_fn_.cpp
// compile with: /EHsc /std:c++17
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
int main()
{
std::vector<int> v1 = { 99, 6264, 41, 18467, 6334, 26500, 19169 };
auto divisible_by_3 = [](int i){ return i % 3 == 0; };
std::cout << "Vector v1 = ( " ;
for (const auto& item : v1)
{
std::cout << item << " ";
}
std::cout << ")" << std::endl;
// Count the number of vector elements divisible by 3.
int divisible =
std::count_if(v1.begin(), v1.end(), divisible_by_3);
std::cout << "Elements divisible by three: "
<< divisible << std::endl;
// Count the number of vector elements not divisible by 3.
int not_divisible =
std::count_if(v1.begin(), v1.end(), std::not_fn(divisible_by_3));
std::cout << "Elements not divisible by three: "
<< not_divisible << std::endl;
}
Vector v1 = ( 99 6264 41 18467 6334 26500 19169 )
Elements divisible by three: 2
Elements not divisible by three: 5
ptr_fun
Fungsi templat pembantu digunakan untuk mengonversi penunjuk fungsi unary dan biner, masing-masing, menjadi fungsi yang dapat diadaptasi unary dan biner. Tidak digunakan lagi di C++11, dihapus di C++17.
template <class Arg, class Result>
pointer_to_unary_function<Arg, Result, Result (*)(Arg)> ptr_fun(Result (*pfunc)(Arg));
template <class Arg1, class Arg2, class Result>
pointer_to_binary_function<Arg1, Arg2, Result, Result (*)(Arg1, Arg2)> ptr_fun(Result (*pfunc)(Arg1, Arg2));
Parameter
pfunc
Penunjuk fungsi unary atau biner yang akan dikonversi ke fungsi yang dapat disesuaikan.
Tampilkan Nilai
Fungsi templat pertama mengembalikan fungsi unary pointer_to_unary_function<Arg
, Result
>(* ). pfunc
Fungsi templat kedua mengembalikan fungsi biner pointer_to_binary_function<Arg1
, , Result
Arg2
>(* ). pfunc
Keterangan
Penunjuk fungsi adalah objek fungsi. Ini dapat diteruskan ke algoritma apa pun yang mengharapkan fungsi sebagai parameter, tetapi tidak dapat disesuaikan. Informasi tentang jenis berlapisnya diperlukan untuk menggunakannya dengan adaptor, misalnya, untuk mengikat nilai ke dalamnya atau untuk meniadakannya. Konversi penunjuk fungsi unary dan biner oleh fungsi pembantu ptr_fun
memungkinkan adaptor fungsi untuk bekerja dengan penunjuk fungsi unary dan biner.
Contoh
// functional_ptr_fun.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <functional>
#include <cstring>
#include <iostream>
int main( )
{
using namespace std;
vector <char*> v1;
vector <char*>::iterator Iter1, RIter;
v1.push_back ( "Open" );
v1.push_back ( "up" );
v1.push_back ( "the" );
v1.push_back ( "opalescent" );
v1.push_back ( "gates" );
cout << "Original sequence contains: " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; ++Iter1 )
cout << *Iter1 << " ";
cout << endl;
// To search the sequence for "opalescent"
// use a pointer_to_function conversion
RIter = find_if( v1.begin( ), v1.end( ),
not1 ( bind2nd (ptr_fun ( strcmp ), "opalescent" ) ) );
if ( RIter != v1.end( ) )
{
cout << "Found a match: "
<< *RIter << endl;
}
}
ref
Membuat reference_wrapper
dari argumen.
template <class Ty>
reference_wrapper<Ty> ref(Ty& arg);
template <class Ty>
reference_wrapper<Ty> ref(reference_wrapper<Ty>& arg);
Tampilkan Nilai
Referensi ke arg
; khususnya, reference_wrapper<Ty>(arg)
.
Contoh
Contoh berikut mendefinisikan dua fungsi: satu terikat ke variabel string, yang lain terikat ke referensi variabel string yang dihitung oleh panggilan ke ref
. Ketika nilai variabel berubah, fungsi pertama terus menggunakan nilai lama dan fungsi kedua menggunakan nilai baru.
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <ostream>
#include <string>
#include <vector>
using namespace std;
using namespace std;
using namespace std::placeholders;
bool shorter_than(const string& l, const string& r)
{
return l.size() < r.size();
}
int main()
{
vector<string> v_original;
v_original.push_back("tiger");
v_original.push_back("cat");
v_original.push_back("lion");
v_original.push_back("cougar");
copy(v_original.begin(), v_original.end(), ostream_iterator<string>(cout, " "));
cout << endl;
string s("meow");
function<bool (const string&)> f = bind(shorter_than, _1, s);
function<bool (const string&)> f_ref = bind(shorter_than, _1, ref(s));
vector<string> v;
// Remove elements that are shorter than s ("meow")
v = v_original;
v.erase(remove_if(v.begin(), v.end(), f), v.end());
copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
cout << endl;
// Now change the value of s.
// f_ref, which is bound to ref(s), will use the
// new value, while f is still bound to the old value.
s = "kitty";
// Remove elements that are shorter than "meow" (f is bound to old value of s)
v = v_original;
v.erase(remove_if(v.begin(), v.end(), f), v.end());
copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
cout << endl;
// Remove elements that are shorter than "kitty" (f_ref is bound to ref(s))
v = v_original;
v.erase(remove_if(v.begin(), v.end(), f_ref), v.end());
copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
cout << endl;
}
tiger cat lion cougar
tiger lion cougar
tiger lion cougar
tiger cougar
swap
Tukar dua function
objek.
template <class FT>
void swap(function<FT>& f1, function<FT>& f2);
Parameter
FT
Jenis yang dikontrol oleh objek fungsi.
f1
Objek fungsi pertama.
f2
Objek fungsi kedua.
Keterangan
Fungsi mengembalikan f1.swap(f2)
.
Contoh
// std__functional__swap.cpp
// compile with: /EHsc
#include <functional>
#include <iostream>
int neg(int val)
{
return (-val);
}
int main()
{
std::function<int (int)> fn0(neg);
std::cout << std::boolalpha << "empty == " << !fn0 << std::endl;
std::cout << "val == " << fn0(3) << std::endl;
std::function<int (int)> fn1;
std::cout << std::boolalpha << "empty == " << !fn1 << std::endl;
std::cout << std::endl;
swap(fn0, fn1);
std::cout << std::boolalpha << "empty == " << !fn0 << std::endl;
std::cout << std::boolalpha << "empty == " << !fn1 << std::endl;
std::cout << "val == " << fn1(3) << std::endl;
return (0);
}
empty == false
val == -3
empty == true
empty == true
empty == false
val == -3
Saran dan Komentar
https://aka.ms/ContentUserFeedback.
Segera hadir: Sepanjang tahun 2024 kami akan menghentikan penggunaan GitHub Issues sebagai mekanisme umpan balik untuk konten dan menggantinya dengan sistem umpan balik baru. Untuk mengetahui informasi selengkapnya, lihat:Kirim dan lihat umpan balik untuk