gpt4 book ai didi

c++ - 模板中模板类型相关结构的特化

转载 作者:太空狗 更新时间:2023-10-29 20:37:46 27 4
gpt4 key购买 nike

我正在尝试创建模板类的部分特化成员,其中内部类的模板类型是来自外部类的模板类型......如下:

template<typename T>
struct Num
{
template <T n>
struct VH
{
enum { value = n };
T v = value;
};
};

template <typename T> struct Num<T>::VH<0>
{
enum {value = 1};
T v = value;
};

template <typename T> struct Num<T>::VH<1>
{
enum {value = 0};
T v = value;
};

失败了

error: too few template-parameter-lists
template <typename T> struct Num<T>::VH<0>

以及以下内容:

template <typename T> struct Num<T>::template<> VH<0>
{
enum {value = 0};
T v = value;
};

template <typename T> struct Num<T>::template<> VH<1>
{
enum {value = 1};
T v = value;
};

只是感觉不对 (error: expected template-id before '<' token
template <typename T> struct Num<T>::template<> VH<0>
)

阅读后 explicit specialization of template class member function以下

template <typename T> template<> struct Num<T>::VH<0>
{
enum {value = 0};
T v = value;
};

template <typename T> template <> struct Num<T>::VH<1>
{
enum {value = 1};
T v = value;
};

给出错误:

error: invalid explicit specialization before '>' token
template <typename T> template<> struct Num<T>::VH<0>
^
error: enclosing class templates are not explicitly specialized
error: template parameters not used in partial specialization:
template <typename T> template<> struct Num<T>::VH<0>
^
error: 'T'

任何人都可以让我知道正确的语法,我现在似乎无法弄清楚......?

最佳答案

语法是

template <typename T>
template <>
struct Num<T>::VH<0>
{
enum {value = 1};
T v = value;
};

但不幸的是,完全特化一个内部结构是不可能的。但是你可以部分地专门化它:

template<typename T>
struct Num
{
template <T n, int dummy = 0> // Add extra dummy for partial specialization
struct VH
{
enum { value = n };
T v = value;
};
};

template <typename T>
template <int dummy>
struct Num<T>::VH<0, dummy>
{
enum {value = 1};
T v = value;
};

Demo

关于c++ - 模板中模板类型相关结构的特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33758287/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com