基于非类型模板参数的重载

Overloading based on non-type template parameter

本文关键字:参数 重载 于非 类型      更新时间:2023-10-16

我们熟悉基于函数参数的重载。但是为什么我们不能基于非类型模板参数进行重载呢?对于此类重载,您不必仅仅出于重载目的添加额外的函数参数,这可能会对运行时性能产生负面影响。唉,以下代码无法编译:

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 还是浮点数等)。

你应该让它超载,不要担心影响,它并不像你想象的那么糟糕。如果函数之间的行为差异足够大,则不应使用模板