我们熟悉基于函数参数的重载。但是为什么我们不能基于非类型模板参数进行重载呢?通过这种重载,您不必仅仅为了重载目的而添加额外的函数参数,这可能会对运行时性能产生负面影响。唉,下面的代码无法编译:
template <bool>
void func() {}
template <int>
void func() {}
int main() {
func<0>();
}
产生的错误消息是
error: call of overloaded 'func()' is ambiguous
func<0>();
^
note: candidate: void func() [with bool <anonymous> = false]
void func() {}
^
note: candidate: void func() [with int <anonymous> = 0]
void func() {}
^
请注意,这可能比
void func(bool) {}
void func(int) {}
允许这种使用有什么问题吗?
如果您愿意添加一些语法,您可以使用:
// No default implementation.
template <typename T, T value> struct Impl;
// Implement the bool/true version
template <> struct Impl<bool, true>
{
void operator()() {}
};
// Implement the bool/false version
template <> struct Impl<bool, false>
{
void operator()() {}
};
// Implement the int version
template <int N> struct Impl<int, N>
{
void operator()() {}
};
template <typename T, T value>
void func()
{
Impl<T, value>()();
};
int main()
{
func<bool, true>();
func<int, 10>();
}
免责声明
我不知道这是否会比调用更好func(true)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)