从拥抱类型中获取模板参数的值
Getting value of template parameter from embracing type
假设我有一个模板类,它有一个整数形参:
template <int N>
class A
{
public:
static int get_N()
{
return N;
}
};
template<typename T>
class B
{
public:
B()
{
cout << "N = " << T::get_N() << endl; // Accessing N via the auxiliary method
}
};
要在类B中引用N模板参数,我必须在a中创建一个辅助方法。我希望这样做:
template <int N>
class A
{
};
template<typename T>
class B
{
public:
B()
{
cout << "N = " << T::N << endl; // Accessing N directly
}
};
问题是我将有很多a模板专门化,我真的不想把这个辅助方法复制到所有的专门化类中,我也不想为此引入继承。有可能实现我想要的吗?
您可以从专门化中推断出该值:
#include <iostream>
template <typename T> struct get_N;
template <template <int N> class T, int N>
struct get_N<T<N>> {
static constexpr int value = N;
};
template <int N> struct A {};
template <typename T>
struct B {
void f() { std::cout << get_N<T>::value << 'n'; }
};
int main() {
B<A<10>>().f();
}
您可以这样提取N
:
template<typename A>
struct get_N;
template<int N>
struct get_N<A<N> > : std::integral_constant<int,N> { };
这样,您就不需要在每个A
专门化中定义任何内容,但是您可以这样说:
using X = A<3>;
cout << "N = " << get_N<X>() << endl; // prints: N = 3
然而,我可能仍然更喜欢让A
派生一个轻量级模板类,它只定义一个static constrexpr
变量,就像juanchopanza的答案一样。然后每个A
专门化看起来像
template<>
struct A<3> : A_base<3> { ... };
还不错。事实上,再次查看两个选项,我看到A_base
只不过是
template<int N>
using A_base = std::integral_constant<int,N>;
,所以它可以被赋予一个更通用的短名称。我通常叫它num
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 有没有办法在从编译器获取参数时避免预处理器宏?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 如何从参数中获取函数签名?
- 获取可变参数模板参数包的相关类型
- 在 C++11 中获取函子作为参数
- 如何使用可变参数模板获取参数的变量号及其大小C++
- 是否可以获取成员函数模板参数的拥有对象?
- 如何从 x64 程序集中的堆栈中获取参数?
- 获取第一个模板参数的可靠方法
- 如何从参数包获取指向对象的指针
- C++ 如何使派生类自动获取基类参数
- 通过命令行参数获取llvm ir文件时面临问题
- 在C++中,是否允许将函数指针强制转换为将指向基类或派生类的指针作为参数获取的函数指针
- 使用一个可选参数获取两个参数到main
- cpp 映射作为函数参数获取警告信息 "discards qualifiers"
- 从控制台应用中的命令行参数获取文件名C++
- 从模板参数获取函数参数
- 使用参数获取其他参数