在定义何时重载之前声明函数模板

Ant*_*ant 3 c++ templates overloading c++11

C++ Primer第5版在第16.3章(讨论函数模板重载的章节)结尾处有一小段建议:

在定义任何函数之前,声明重载集中的每个函数.这样您就不必担心编译器在看到您打算调用的函数之前是否会实例化一个调用.

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

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

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

R S*_*ahu 5

作者警告你:

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");
}

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

template <typename T> void test(T*)
{ 
}
Run Code Online (Sandbox Code Playgroud)

还有这些:

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

如果您不提供声明

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

void test(int *);
Run Code Online (Sandbox Code Playgroud)

以前main,他们不会匹配main.