[英]Why is it necessary to specify the type in this C++ template?
我有這個最小的,人為的C ++代碼示例,帶有一個默認類型參數的模板結構:
#include <iostream>
using namespace std;
template <class T=int>
struct AddsFourtyTwo {
template <class U>
static U do_it(U u) {
return u + static_cast<T>(42);
}
};
int main() {
double d = 1.24;
std::cout << AddsFourtyTwo::do_it(d) << std::endl;
}
當我嘗試編譯此代碼時,我得到g ++ 4.9.1的以下錯誤:
$ g++ test.cpp
test.cpp: In function 'int main()':
test.cpp:14:18: error: 'template<class T> struct AddsFourtyTwo' used without template parameters
std::cout << AddsFourtyTwo::do_it(d) << std::endl;
^
如果我為T指定int,那么它編譯並產生預期的輸出(43.24)。 我的問題是,為什么這有必要呢? 如果您需要指定類型,默認類型參數在AddsFourtyTwo的定義中會做什么?
您不需要指定類型,但語言不允許使用模板作為實際類型而不指定某個參數列表:
std::cout << AddsFourtyTwo<>::do_it(d) << std::endl;
使用模板類需要以下語法:
std::cout << AddsFourtyTwo<>::do_it(d) << std::endl;
將編譯並使用默認參數。 這是令人困惑的,因為模板化方法不需要相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.