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

c – 在定义重载时声明函数模板

发布时间:2020-12-16 10:00:10 所属栏目:百科 来源:网络整理
导读:C Primer第5版在第16.3章(讨论函数模板重载的章节)末尾有一小段建议: Declare every function in an overload set before you define any of the functions. That way you don’t have to worry whether the compiler will instantiate a call before it se
C Primer第5版在第16.3章(讨论函数模板重载的章节)末尾有一小段建议:

Declare every function in an overload set before you define any of the
functions. That way you don’t have to worry whether the compiler will
instantiate a call before it sees the function you intended to call.

那么这告诉我,在重载解析期间选择候选和可行函数时,编译器可能会实例化最终未选择的函数模板吗?我试着看看这是否真的会发生:

template<class> struct always_false : std::false_type {};

template <typename T> void test(T const &){
    static_assert(always_false<T>::value,"If this fires,it is instantiated");
}

template <typename T> void test(T*) {   }

int main(){
    int *q = nullptr; 
    test(q); //test(T*) should be the best match
}

如果test(T const&)以任何形式实例化,则该程序将抛出编译器错误,除非程序按预期编译良好.那么什么样的编译事故就是小费试图阻止我?什么时候它会在看到我试图调用的函数之前实例化一个函数?

解决方法

作者警告你:

template<class> struct always_false : std::false_type {};

template <typename T> void test(T const &){
   static_assert(always_false<T>::value,it is instantiated");
}

int main(){
    int *q = nullptr; 
    test(q); //test(T*) will not be matched.
}

template <typename T> void test(T*)
{ 
}

还有这些:

template<class> struct always_false : std::false_type {};

template <typename T> void test(T const &){
   static_assert(always_false<T>::value,it is instantiated");
}

template <> void test<int>(int const &);

void test(int *);

int main(){
   int *q = nullptr; 
   test(q); //test(int*) should be the best match
   int a;
   test(a); // test<int>(int const&) should be the best match
}

template <> void test<int>(int const &)
{
}

void test(int *)
{ 
}

如果您不提供声明

template <> void test<int>(int const &);

void test(int *);

在主要之前,他们将不会在主要匹配.

(编辑:李大同)

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

    推荐文章
      热点阅读