采用类型 T 的包的模板
template which takes a pack of type T
我有以下按预期编译和执行的最小代码片段:
template < class T, T... Chrs>
struct mystring
{
static auto c_str()
{
static char str[] = {Chrs..., 0};
return str;
}
};
template <class T, T... Chrs>
auto operator""_t()
{
return mystring<T, Chrs...>();
}
int main()
{
auto x = "Hallo"_t ;
std::cout << x.c_str() << std::endl;
}
问题:
是否可以使用以下方式编写模板 mystring
:
auto x = mystring<'a','b','c'>();
还有
auto x = mystring< 1,2,3> ();
或任何其他类型。
我不知道如何写类似(伪代码)的东西:
template < T ... Chrs> // how to define T here?
struct mystring
{ }
也不允许以下内容:
template <typename T, T ...Chrs >
struct mystring<T...Chrs> {};
与您现在使用的方法相同。除了不使用 T
,其中 T
是模板参数,直接使用 char
即可:
template <char... Chrs>
struct mystring
{
/* rest as before */
};
当然,这现在只适用于 char
而不是 wchar_t
(但话又说回来,原来的也是如此)
您可以通过编写如下内容来概括这一点:
template <class T, T... Vals>
struct array { ... };
template <char... Chrs>
using mystring = array<char, Chrs...>;
在 C++17 中,我们将有 template auto
让你写:
template <auto... Vals>
struct array { /* .. */ };
然后由您来验证所有 Vals
是否为同一类型。也许通过:
template <auto Val, decltype(Val)... Vals>
struct array { /* .. */ };
我有以下按预期编译和执行的最小代码片段:
template < class T, T... Chrs>
struct mystring
{
static auto c_str()
{
static char str[] = {Chrs..., 0};
return str;
}
};
template <class T, T... Chrs>
auto operator""_t()
{
return mystring<T, Chrs...>();
}
int main()
{
auto x = "Hallo"_t ;
std::cout << x.c_str() << std::endl;
}
问题:
是否可以使用以下方式编写模板 mystring
:
auto x = mystring<'a','b','c'>();
还有
auto x = mystring< 1,2,3> ();
或任何其他类型。
我不知道如何写类似(伪代码)的东西:
template < T ... Chrs> // how to define T here?
struct mystring
{ }
也不允许以下内容:
template <typename T, T ...Chrs >
struct mystring<T...Chrs> {};
与您现在使用的方法相同。除了不使用 T
,其中 T
是模板参数,直接使用 char
即可:
template <char... Chrs>
struct mystring
{
/* rest as before */
};
当然,这现在只适用于 char
而不是 wchar_t
(但话又说回来,原来的也是如此)
您可以通过编写如下内容来概括这一点:
template <class T, T... Vals>
struct array { ... };
template <char... Chrs>
using mystring = array<char, Chrs...>;
在 C++17 中,我们将有 template auto
让你写:
template <auto... Vals>
struct array { /* .. */ };
然后由您来验证所有 Vals
是否为同一类型。也许通过:
template <auto Val, decltype(Val)... Vals>
struct array { /* .. */ };