是否可以 declare/implement 函数范围内的模板?
Is it possible to declare/implement a template within a function scope?
标题 == 问题。
具体来说,是否可以这样实现std::sinh?
namespace std {
long double sinh(const long double arg) {
template <long double _arg> long double _sinh() {
// sinh implementaion here
}
template <> long double _sinh<0>() {return 0;}
template <> long double _sinh<-0>() {return -0;}
template <> long double _sinh<INFINITY>() {return INFINITY;}
template <> long double _sinh<-INFINITY>() {return -INFINITY;}
return _sinh<arg>();
}
}
我知道,这是一个愚蠢的想法,但我真的很好奇。
有两三个问题:
- 模板参数不能有浮点类型
- 模板参数必须是常量表达式,这排除了函数参数。
- 函数定义只能在命名空间范围内。如果您出于某种原因想让它无法访问,您可以将其设置为 lambda 或本地 class 的成员。
Is it possible to declare/implement a template within a function scope?
没有。 [温度]/p2:
A template-declaration can appear only as a namespace scope or class scope declaration.
以免您认为这允许在本地 类、[temp.mem]/p2:
内进行模板声明
A local class of non-closure type shall not have member templates.
您的代码还存在其他各种问题,Mike Seymour 的回答中提到了其中两个问题。
虽然 sinh
之类的东西很可能可以作为 constexpr
函数实现,如果参数是常量表达式,则允许在编译时求值。
标题 == 问题。
具体来说,是否可以这样实现std::sinh?
namespace std {
long double sinh(const long double arg) {
template <long double _arg> long double _sinh() {
// sinh implementaion here
}
template <> long double _sinh<0>() {return 0;}
template <> long double _sinh<-0>() {return -0;}
template <> long double _sinh<INFINITY>() {return INFINITY;}
template <> long double _sinh<-INFINITY>() {return -INFINITY;}
return _sinh<arg>();
}
}
我知道,这是一个愚蠢的想法,但我真的很好奇。
有两三个问题:
- 模板参数不能有浮点类型
- 模板参数必须是常量表达式,这排除了函数参数。
- 函数定义只能在命名空间范围内。如果您出于某种原因想让它无法访问,您可以将其设置为 lambda 或本地 class 的成员。
Is it possible to declare/implement a template within a function scope?
没有。 [温度]/p2:
A template-declaration can appear only as a namespace scope or class scope declaration.
以免您认为这允许在本地 类、[temp.mem]/p2:
内进行模板声明A local class of non-closure type shall not have member templates.
您的代码还存在其他各种问题,Mike Seymour 的回答中提到了其中两个问题。
虽然 sinh
之类的东西很可能可以作为 constexpr
函数实现,如果参数是常量表达式,则允许在编译时求值。