2010-04-13 106 views
3
template<class T> 
class test 
{ 
    public: 
     test() 
     { 
     } 

     test(T& e) 
     { 
     } 

}; 

int main() 
{ 

    test<double> d(4.3); 

    return 0; 
} 

使用G ++ 4.4.1以下錯誤編譯:C++模板:隱式轉換,沒有匹配的函數調用構造函數

g++ test.cpp -Wall -o test.exe 
test.cpp: In function 'int main()': 
test.cpp:18: error: no matching function for call to 'test<double>::test(double) 
' 
test.cpp:9: note: candidates are: test<T>::test(T&) [with T = double] 
test.cpp:5: note:     test<T>::test() [with T = double] 
test.cpp:3: note:     test<double>::test(const test<double>&) 
make: *** [test.exe] Error 1 

然而,這個工程:

double a=1.1; 
test<double> d(a); 

爲什麼這是不是? 有沒有可能g ++不能隱式地將字面表達式1.1轉換爲double? 謝謝。

+0

您的構造函數不需要double,它需要對double的引用。 – 2010-04-13 10:16:02

回答

3

這是由於您的構造函數定義中的引用(&)。你不能通過引用傳遞一個常量值,只有像你的第二個例子那樣的變量。

+0

爲什麼downvote?答案是正確的。 – 2010-04-13 10:17:40

2

您不能將雙重字面值綁定到(非const)雙重字符&。

您是不是要將它作爲T const &或按值傳遞? (可用於迄今爲止給出的代碼。)

2

您不能對非臨時引用採用非const引用。試着改變你的構造函數

test(const T& e) 
    { 
    } 

或按值傳遞:

test(T e) 
    { 
    } 
8

你傳遞的雙重1.1到非const引用T&。這意味着你必須通過一個有效的左值的構造如通過做:

double x = 4.3; 
test<double> d(x); 

使構造帶const引用(const T&)和它的作品,因爲你被允許綁定的臨時(右值)以const引用,4.3在技術上是一個臨時的雙。

相關問題