模板——传递变量而不是值
Templates - Passing variable instead of value
我有一个模板:
template<unsigned int N> struct IntN;
template <> struct IntN< 8> {
typedef uint8_t type;
};
template <> struct IntN<16> {
typedef uint16_t type;
};
在main中,我这样初始化和交替:
IntN< 8>::type c;
这似乎可以工作,但是,当我将值存储在变量中时,它不起作用,我得到以下错误:
下面是一个示例代码:错误:'int'类型的非类型模板参数不是整型常量表达式
template<unsigned int N> struct IntN;
template <> struct IntN< 8> {
typedef uint8_t type;
};
template <> struct IntN<16> {
typedef uint16_t type;
};
int main(int argc, char *argv[]) {
int foo = 8;
IntN<foo>::type c;
}
有人有什么想法吗?由于
整型模板形参的模板实参必须是常量表达式。整型文字是一个常量表达式
IntN<8>::type c;
用常量表达式初始化的常量变量是常量表达式
const int n = 8;
IntN<n>::type c;
这里n是可以的,因为它既是const,又是由常量表达式(8)初始化的。
int n = 8;
const int m = n;
IntN<n>::type c; //error n is not const therefore not a constant expression
IntN<m>::type c; //error m is const but initialized with a non-constant expression therefore not a constant expression
函数模板是一个蓝图,它告诉编译器当实例化时(即当你在代码中使用模板函数时)如何为函数生成代码。
确切地说,编译器将生成的取决于模板形参的实例化值。这些值必须已知并最终确定,否则编译器不知道生成什么代码。
相关文章:
- 没有用于初始化C++中的变量模板的匹配构造函数
- C++:是否可以使用非静态成员变量模板?
- 为变量模板的每个参数调用模板函数
- 使用变量模板的递归计算 - gcc 与 clang
- 如何使用变量模板比较 C++ 17 中的变量类型?
- 使用语法公开派生类中的基类别名模板和变量模板?
- 变量模板的部分专用化
- 主函数体未检测到对重载可变变量模板化函数C++的调用
- 非 constexpr 变量模板的开销是否为零?
- c++ 使用 CRTP 为变量模板中的每个类型创建纯虚拟重载
- SFINAE的变分变量模板专门化
- 变量模板,具有与实例一样多的参数
- 将变量模板限制为类型列表
- 变量模板是否可以作为模板模板参数传递
- GCC5:嵌套变量模板不是函数模板?
- 变量模板专用化
- 变量模板的显式专用化
- 模板别名、变量模板和自动类型推断无法推断模板参数
- C 变量模板.这是UB
- 变量模板中的除法在 Visual Studio 2017 中返回零