How to use variadic templates and template metaprogramming to accept different type as input

137 views Asked by At

How to use variadic templates and template metaprogramming to accept different type as input?

//This template takes variable number of c++ char and add'\0' 
//to the end to mimic the c_str() inbuilt function 
template<char ...Cs> struct listChar 
{
    constexpr std::array<char, 1 + sizeof...(Cs)> cTypeStr() 
    {
        return { {Cs..., '\0'} };
    }
};

int main(int argc, char** argv)
{
    auto temp1 = listChar<'C','H','A','N','G','E'>::cTypeStr();//This works
    //auto temp2 = listChar<"Change">::cTypeStr(); // Do not work
    //auto temp3 = listChar<"Change",'C','H','A','N','G','E'>::cTypeStr();//Do not work 
    cout << "Output: \n" << spStr.data();
    getchar();
    return 0;
}
1

There are 1 answers

1
Pedro Boechat On

If you don't need to build the string at compile time, here's a much simpler approach that doesn't involve variadic templates or type traits:

#include <iostream>
#include <string>

template <int N, bool fizz, bool buzz>
struct _FizzBuzz;

template <int N>
struct FizzBuzz : _FizzBuzz<N, N % 3 == 0, N % 5 == 0>
{
};

template <>
struct FizzBuzz<1>
{
    static std::string str()
    {
        return "1";
    }
};

template <int N>
struct _FizzBuzz<N, true, true>
{
    static std::string str()
    {
        return FizzBuzz<N - 1>::str() + "\nFizzBuzz";
    }

};

template <int N>
struct _FizzBuzz<N, true, false>
{
    static std::string str()
    {
        return FizzBuzz<N - 1>::str() + "\nFizz";
    }

};

template <int N>
struct _FizzBuzz<N, false, true>
{
    static std::string str()
    {
        return FizzBuzz<N - 1>::str() + "\nBuzz";
    }

};

template <int N>
struct _FizzBuzz<N, false, false>
{
    static std::string str()
    {
        return FizzBuzz<N - 1>::str() + "\n" + std::to_string(N);
    }

};


int main(int argc, char** argv)
{
    auto spStr = FizzBuzz<47>::str();
    std::cout << "Your Output: \n" << spStr;
    getchar();
    return 0;
}