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

Lin*_*gxi 5 c++ templates overloading language-lawyer

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

template <bool>
void func() {}

template <int>
void func() {}

int main() {
  func<0>();
}
Run Code Online (Sandbox Code Playgroud)

产生的错误信息是

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() {}
          ^
Run Code Online (Sandbox Code Playgroud)

请注意,这可能比

void func(bool) {}

void func(int) {}
Run Code Online (Sandbox Code Playgroud)

允许这种用法有问题吗?

Ami*_*ory 1

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;
}
Run Code Online (Sandbox Code Playgroud)