微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)时,两个重载之间存在奇怪的交互.因为我不确定指导它的基础规则.)

原文地址:https://www.jb51.cc/c/111785.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐