gpt4 book ai didi

c++ - 为什么浮点类型对于模板函数来说是无效的模板参数类型?

转载 作者:搜寻专家 更新时间:2023-10-31 01:52:58 27 4
gpt4 key购买 nike

我在一个网站上看到声明

template <int x>
int func() {
return x;
}

有效而以下无效

template <double x>
double func() {
return x;
}

为什么第一个是模板函数的合法声明而第二个不是?

最佳答案

它是无效的,因为它不是整型。非类型模板参数有一定的限制,这是其中之一,它说......

Floating-point numbers and class-type objects are not allowed as nontype template parameters.

template <double VAT>       // ERROR: floating-point values are not
double process(double v) { // allowed as template parameters
return v * VAT;
}

template <std::string name> // ERROR: class-type objects are not
class MyClass { // allowed as template parameters
/* ... */
};

以上内容转自C++ Templates .我不为此付出任何代价。

根据我的理解,它们对模板初始化无效的原因是因为像 float 和 double 这样的类型在 C++ 中没有定义的实现。所以当像

这样的模板时
template <double VAT> double process(double v);

用两个不同的 double 值初始化为

template <(double) 2/3> double process(2.3)

template <(double) 1/3> double process(2.4);

由于双非类型,它们可能具有不同的位表示,这会使编译器感到困惑。

关于c++ - 为什么浮点类型对于模板函数来说是无效的模板参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11806091/

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