如何使用可变参数模板和模板元编程来接受不同类型的输入

问题描述

如何使用可变参数模板和模板元编程来接受不同类型的输入?

//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','E'>::cTypestr();//Do not work 
    cout << "Output: \n" << spStr.data();
    getchar();
    return 0;
}

解决方法

如果您不需要在编译时构建字符串,这是一种更简单的方法,它不涉及可变参数模板或类型特征:

var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
Console.WriteLine(((utcOffset < TimeSpan.Zero) ? "-" : "+") + utcOffset.ToString("hhmm"));