c++ 11 變長參數模板

#include <iostream>
#include <typeinfo>
#include <string>
#include <sstream>
using namespace std;
#include <stdio.h>
#include <stdarg.h>

//////////////////////////////////////////////////////////////////////////////////
template <typename... TS>
static int MyPrint(const char* s, TS... args)
{
    return printf(s, args...);
}

template <typename... TS>
static void DummyIter(TS... args)
{
}

template <typename T>
static T Show(T t, int i)
{
    cout << "value:" << t << " ,index:" << i << endl;
    return t;
}

template <typename... TS>
static void Func(TS... args)
{
    int index = 0;
    DummyIter(Show(args, index++)...);
}

template <typename T>
string ToString(T t)
{
    stringstream stream;
    stream << t;
    return stream.str();
}

template <typename... Types>
static void Foo(Types... args)
{
    DummyIter(MyPrint("type(%s):%s, ", ToString(args).c_str(), typeid(args).name()) ...);
    MyPrint("\n");
}
//////////////////////////////////////////////////////////////////////////////////
//繼承
template <typename... Types>
struct VariadicStruct : Types...
{
    VariadicStruct()
    {
        DummyIter(MyPrint("type:%s\n", typeid(Types).name()) ...);
    }
};

template <typename... Types>
static void ConstructStruct(void)
{
    VariadicStruct<Types...>();
}
template void ConstructStruct<>(void);
//////////////////////////////////////////////////////////////////////////////////

template <typename... Types>
static void f(Types... args)
{
    printf("values:%f, %f\n", args...);
}

template<> void f<>()
{
    cout << "no arguments!" << endl;
}
//////////////////////////////////////////////////////////////////////////////////

template <typename T1, typename T2>
static auto h(T1 t1, T2 t2) -> decltype(t1 * t2)
{
    return t1 * t2;
}

template <typename... Types>
static void g(Types... args)
{
    f(h(args...) + args ...);
}
//////////////////////////////////////////////////////////////////////////////////
int main()
{
    MyPrint("%s, c++ %d\n", "Hello world", 11);

    Func(-100, 0.5);

    Foo(3, "Hello", 0.25, 10, 1.33, "xxxxx");

    struct A {};
    struct B {};
    ConstructStruct<A, B>();
    ConstructStruct<>();

    g(0.1, 20);
    g<>();

    return 0;
}
相關文章
相關標籤/搜索