c++ - 使用模板特化选择合适的类型

标签 c++ templates

这是模板规范化的代码:

template <int i>
struct userInput{};

template <>
struct userInput<1>
{
typedef int typeName;
};

template <>
struct userInput<2>
{
typedef double typeName;
};

我想根据用户输入选择合适的模板:

int i;
std::cin>>i;
userInput<i>::typeName ty;

但是编译器对我不满意,它要求将一个常量值传递给模板参数。 所以我这样做了:

int i;
std::cin>>i;    
const int p = i;
userInput<p>::typeName ty;

但是,出现错误:模板参数'i':'num':局部变量不能用作非类型参数。任何人都可以帮助我吗?我将不胜感激!

最佳答案

非类型模板参数需要常量编译时表达式,因为它们是在编译期间实例化的:

const int x = 1;
int y = 1;
userInput<x>::typeName a; // valid
userInput<1>::typeName a; // valid
userInput<y>::typeName b; // invalid, what should be instantiated?

没有办法实现你想做的事情,因为 p 常量将在运行时初始化。

关于c++ - 使用模板特化选择合适的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11217457/

相关文章:

c++ - 如何检查内存分配是否仍然有效?

c++ - 处理二进制数据和无符号字符

模板构造函数中的 C++ 链接器错误 : "unresolved external symbol"

C++ 部分模板 模板特化

c++ - 为什么调整 vector 大小比 Reserve 和 Push_back 更快?

c++ - 从包含层次结构生成单个包含文件

c++ - Win32 事件与信号量

c++ - 为什么临时成员函数不绑定(bind)到正确的类型?

c++ - 专门化模板定义中的模板成员

c++ - 具有继承性的模板如何显式调用其父级的构造函数?