基于非类型模板参数的重载
Overloading based on non-type template parameter
我们熟悉基于函数参数的重载。但是为什么我们不能基于非类型模板参数进行重载呢?对于此类重载,您不必仅仅出于重载目的添加额外的函数参数,这可能会对运行时性能产生负面影响。唉,以下代码无法编译:
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)
表现更好.
Andrei Alexandrescu在IIUC的"现代C++设计"中写过这个,看起来std::integral_constant
基本上可以给出你想要的效果,不是吗?与以下方面相比,主要改进是什么?它基本上允许对常量(至少是整数类型)进行重载。
#include <type_traits>
using tt = std::integral_constant<bool, true>;
constexpr tt t;
using ft = std::integral_constant<bool, false>;
constexpr ft f;
void func(tt) {};
void func(ft) {};
int main()
{
func(t);
return 0;
}
你为什么要这样做?
模板是为具有不同类型时函数行为相似的情况而设计的(例如查找最大值,只要该类型支持运算符">",就可以找到最大值。不管是 int 还是浮点数等)。
你应该让它超载,不要担心影响,它并不像你想象的那么糟糕。如果函数之间的行为差异足够大,则不应使用模板
相关文章:
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 如何使用类的参数重载运算符+?
- 为什么我不能用两个参数重载 C++ 运算符 []?
- 模板化类参数重载
- 模板参数重载,最后一个参数为非类型名
- MSVC编译器错误将模板与枚举参数重载时
- std::map:使用键类以外的参数重载运算符<
- C++用参数重载友元类函数参数
- 如何在参数重载解析中禁用隐式转换为指向 void 的指针
- 使用可选参数重载 new 和 delete 运算符
- 如何通过参数函子参数重载函数切换
- 同时使用参数重载和返回类型重载
- 特征3,并根据模板参数重载新算子,以确保正确对齐
- C++使用默认参数重载
- 单例方案,使用不同的参数重载 getInstance
- 具有'const'参数重载的可变参数模板
- 是fill_n,并填充相同的函数,但具有不同的参数重载
- 用不同的参数重载运算符两次
- 模板非类型参数重载
- 无法推断模板参数/'n'重载都无法覆盖所有参数类型