c – 防止隐式模板实例化

在像这样的方法过载情况:
struct A
{
  void foo( int i ) { /*...*/ }
  template<typename T> void foo( T t ) { /*...*/ }
}

除非明确命令,否则如何防止模板实例化?:

A a;
a.foo<int>( 1 ); // ok
a.foo<double>( 1.0 ); // ok
a.foo( 1 ); // calls non-templated method
a.foo( 1.0 ); // error

谢谢!

解决方法

您可以引入一个preventdent_type结构来阻止 template argument deduction.
template <typename T>
struct dependent_type
{
    using type = T;
};

struct A
{
  void foo( int i ) { /*...*/ };
  template<typename T> void foo( typename dependent_type<T>::type t ) { /*...*/ }
}

在你的例子中:

a.foo<int>( 1 );      // calls the template
a.foo<double>( 1.0 ); // calls the template
a.foo( 1 );           // calls non-templated method
a.foo( 1.0 );         // calls non-templated method (implicit conversion)

wandbox example

(此行为在cppreference > template argument deduction > non-deduced contexts中解释.)

如果要使a.foo(1.0)出现编译错误,则需要约束第一个重载:

template <typename T> 
auto foo( T ) -> std::enable_if_t<std::is_same<T,int>{}> { }

这种技术使得foo的上述重载只接受int参数:不允许隐式转换(例如float to int).如果这不是您想要的,请考虑TemplateRex的答案.

wandbox example

(使用上面的约束函数,当调用a.foo< int>(1)时,两个重载之间存在奇怪的交互.因为我不确定指导它的基础规则.)

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...