这是模板规范化的代码:
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/