Created
May 26, 2020 09:53
-
-
Save koturn/6cf089b873e505d8316da6bbb988be59 to your computer and use it in GitHub Desktop.
ラムダのオーバーロードのテスト(一時オブジェクトがmoveされるかどうか)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <vector> | |
#if 0 | |
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; | |
template<class... Ts> overloaded(Ts&&...) -> overloaded<std::decay_t<Ts>...>; | |
#else | |
template <typename... Fs> | |
class | |
#if defined(__has_cpp_attribute) && __has_cpp_attribute(nodiscard) | |
[[nodiscard]] | |
#endif // defined(__has_cpp_attribute) && __has_cpp_attribute(nodiscard) | |
overloaded | |
: public Fs... | |
{ | |
public: | |
template < | |
typename... Gs, | |
std::enable_if_t<sizeof...(Fs) == sizeof...(Gs), std::nullptr_t> = nullptr | |
> | |
explicit constexpr overloaded(Gs&& ... gs) noexcept | |
: Fs{std::forward<Gs>(gs)}... | |
{} | |
using Fs::operator()...; | |
}; // class OverloadedFunc | |
template <typename... Fs> | |
overloaded(Fs&&...) | |
-> overloaded<std::decay_t<Fs>...>; | |
#endif | |
class Func | |
{ | |
public: | |
Func() noexcept | |
{ | |
std::cout << "ctor" << std::endl; | |
} | |
Func(const Func&) | |
{ | |
std::cout << "copy-ctor" << std::endl; | |
} | |
Func(Func&&) noexcept | |
{ | |
std::cout << "move-ctor" << std::endl; | |
} | |
~Func() | |
{ | |
std::cout << "dtor" << std::endl; | |
} | |
Func& | |
operator=(const Func&) | |
{ | |
std::cout << "operator=" << std::endl; | |
return *this; | |
} | |
Func& | |
operator=(Func&&) noexcept | |
{ | |
std::cout << "operator= (move)" << std::endl; | |
return *this; | |
} | |
int | |
operator()() const noexcept | |
{ | |
return 42; | |
} | |
}; // class Func | |
int main() | |
{ | |
auto foo = overloaded{ | |
// generic version | |
[](auto a){ return a + a; }, | |
// specialized version | |
[](int a){ return a * 10; }, | |
Func{} | |
}; | |
std::cout << foo(42) << std::endl; | |
std::cout << foo(3.14) << std::endl; | |
using T = int; | |
std::vector<T> v{1, 2, 3}; | |
std::vector<T> result; | |
std::transform( begin(v), end(v), std::back_inserter(result), foo ); | |
for (auto&& e : result) | |
std::cout << e << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment