我遇到了這樣的情況。我在 Windows 10 上使用 g 。
#include <stdio.h>
template<typename _t>
struct test_thing {};
template<typename _t> void test_2(_t) { printf("A"); }
template<typename _t>
void test()
{
//test_2(_t{}); // prints: ABC
::test_2(_t{}); // prints: ABA <-- namespace op, searching different?
}
template<> void test_2(double) { printf("B"); }
template<typename _t> void test_2(test_thing<_t>) { printf("C"); }
int main()
{
test<int>();
test<double>();
test<test_thing<int>>();
return 0;
}
我的問題是命名空間操作為什么/如何改變編譯器搜索要呼叫的函式的方式。編譯器沒有找到與 args 匹配的最專業的模板函式嗎?如果test_2(test_thing<_t>)在上面定義,test它會找到它,但只能用::,而不是下面。
uj5u.com熱心網友回復:
編譯器沒有找到與 args 匹配的最專業的模板函式嗎?
函式模板不能部分特化。最后一個test_2被第一個超載了。
template<typename _t> void test_2(_t) { printf("A"); } // overload #1
template<typename _t>
void test()
{
//test_2(_t{}); // prints: ABC
::test_2(_t{}); // prints: ABA <-- namespace op, searching different?
}
template<> void test_2(double) { printf("B"); } // explicit specialization for overload#1
template<typename _t> void test_2(test_thing<_t>) { printf("C"); } // overload #2
鑒于test_2(_t{});,ADL幫助并找到了第二個多載test_2。因為::test_2(_t{});ADL 不會生效,只能test_2找到第一個(及其專業化)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459534.html
