C++ で関数名のエイリアス

たまに欲しくなるので、ちょっと考えてみた。

[ソース]

#include <numeric>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <type_traits>

#define FUNCNAME_ALIASES(target, name)                            \
    struct {                                                      \
        template<typename ...Args>                                \
        auto                                                      \
        operator ()(Args&&... args) const                         \
        ->decltype(target(std::forward<Args>(args)...)){          \
            return target(std::forward<Args>(args)...);           \
        }                                                         \
    } const name;

FUNCNAME_ALIASES(std::accumulate, fold)
FUNCNAME_ALIASES(std::for_each, loop)


int
main(){
    int v[] = {1, 2, 3, 4, 5};

    loop(std::begin(v), std::end(v), [](int n){
        std::cout << n << std::endl;
    });
    
    int sum = fold(std::begin(v), std::end(v), 0, [](int a, int b){ return a + b; });
    std::cout << sum << std::endl;
    return 0;
}

[出力]

1
2
3
4
5
15

Variadic Templates って便利よねー。