gpt4 book ai didi

c++ - 模板值的公共(public)访问

转载 作者:行者123 更新时间:2023-11-28 02:00:34 25 4
gpt4 key购买 nike

考虑以下几点:

template<int T>
class Test {
public:
constexpr static int A = T;
};

int main(int argsc, char** args) {
std::cout << Test<2>::T << std::endl; // Option 1
std::cout << Test<2>::A << std::endl; // Option 2
}

为什么选项 1 不能编译? static constexpr A 似乎只是一个额外的步骤。是不是 T 不公开?

有没有比创建像上面的 A 这样的可公开访问的成员更简洁的方法来获取 T

最佳答案

Why doesn't option 1 compile?

因为模板参数只是参数的名称。您可以重命名它们,即:

template <class T> struct X;

// refers to same X
template <class U> struct X { ... };

// still the same X
template <class V>
void X<V>::foo() { ... };

出于同样的原因,您可以在声明和定义之间以不同的方式命名您的函数参数。要求模板参数的名称在类模板中自动可见意味着它必须一开始就固定。

Is there a cleaner way to get at T than by creating a publicly accessible member like A above?

创建可公开访问的成员通常是可行的方法。或者,您可以创建外部特征:

template <class T> struct X { using type = T; }; // internal

template <class > struct get_type;
template <class T> struct get_type<X<T>> { using type = T; }; // external

关于c++ - 模板值的公共(public)访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39800471/

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