加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 防止隐式模板实例化

发布时间:2020-12-16 03:19:54 所属栏目:百科 来源:网络整理
导读:在像这样的方法过载情况: struct A{ void foo( int i ) { /*...*/ } templatetypename T void foo( T t ) { /*...*/ }} 除非明确命令,否则如何防止模板实例化?: A a;a.fooint( 1 ); // oka.foodouble( 1.0 ); // oka.foo( 1 ); // calls non-templated me
在像这样的方法过载情况:
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)时,两个重载之间存在奇怪的交互.因为我不确定指导它的基础规则.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读