基于非类型模板参数的重载 [英] Overloading based on non-type template parameter
本文介绍了基于非类型模板参数的重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们熟悉基于函数参数的重载.但是为什么我们不能基于非类型模板参数进行重载呢?使用这种重载,您不必仅出于重载目的而添加额外的函数参数,否则可能会对运行时性能产生负面影响. las,以下代码无法编译:
We are familiar with overloading based on function parameters. But why can't we have overloading based on non-type template parameters? With such overloading, you don't have to add extra function parameters just for overloading purposes, which may have a negative impact on runtime performance. Alas, the following code does not compile:
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) {}
允许这种用法有问题吗?
Is there any problem in allowing this usage?
推荐答案
如果您愿意接受一些新增的语法,则可以使用:
If you are open to a bit of added syntax, you can use:
// 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)
更好.
I have no idea whether this will perform better than calling func(true)
.
这篇关于基于非类型模板参数的重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文