2011-06-15 134 views
4

如果類也是模板,是否可以使用模板參數調用構造函數?C++調用模板類的特定模板構造函數

#include <stdio.h> 
#include <iostream> 

template <class A> 
struct Class 
{ 
    template <class B> 
    Class(B arg) { std::cout << arg << std::endl; } 
}; 

int main() 
{ 
    Class<int> c<float>(1.0f); 
    Class<int>* ptr = new Class<int><float>(2.0f); 
    return 0; 
} 

編輯:所以我想打電話給一個特定的模板的構造函數的唯一方法是用鑄造paramterers打電話給你想要的模板類型:

#include <stdio.h> 
#include <iostream> 

template <class A> 
struct Class 
{ 
    template <class B> 
    Class(B arg) { std::cout << arg << std::endl; } 

    Class(double arg) { std::cout << "double" << std::endl; } 
    Class(float arg) { std::cout << "float" << std::endl; } 
}; 

int main() 
{ 
    Class<int> c(1.0f); 
    Class<int>* ptr = new Class<int>((double)2.0f); 
    return 0; 
} 

//這個輸出: 浮動 double

edit2:但是構造函數模板參數不是構造函數參數本身的一部分會發生什麼?

template <class B, class C> 
Class(B arg) { /* how do you specify ?? C */ } 
+0

請注意,你的構造應該能夠推斷出你傳遞給他的參數的類型,而無需顯式地指定它的參數。 – ereOn 2011-06-15 12:09:41

+0

你能否給這個問題添加一些標點符號?我不知道如何解析它! – juanchopanza 2011-06-15 12:15:48

+0

[this]的可能重複(http://stackoverflow.com/questions/2786946/c-invoke-explicit-template-constructor)。請注意,作爲模板的外部類是無關緊要的。 – 2011-06-15 12:28:59

回答

2

EDIT2:但會發生什麼構造函數,不是的構造函數的參數本身的部分模板參數?

然後你就可以傳遞在具有其編碼

template<typename T> struct encodeType { }; 

struct A { 
    template<typename T, typename U> 
    A(T t, encodeType<U>) { } 
}; 

A a(1, encodeType<float>()); 
+1

這太棒了!模板非常有趣 – 2011-06-19 09:20:26

4

在你給你居然不需要明確給出了template參數來調用構造函數類的例子:

Class<int> c<float>(1.0f); 

提供簡單的參數作爲1.0f是不夠的:

Class<int> c(1.0f); 

同樣的東西也適用於new的例子。話雖如此,我不認爲你可以使用template參數明確調用構造函數(與普通函數不同)。

1
Class<int> c(1.0f); //f in 1.0 makes it float type! 
Class<int>* ptr = new Class<int>(2.0f); 

這就夠了。它會調用具有模板參數float的構造函數。從參數1.0f,編譯器將推斷構造函數模板的類型參數。由於1.0ffloat,所以編譯器推斷的類型參數是float

同樣看到這些:

Class<int> c(1.0); //this will invoke Class<int><double>(double); 
Class<int>* ptr = new Class<int>(2); //this will invoke Class<int><int>(int); 
1

你需要明確指出與類本身(這是在你的例子A)進入模板類型。但是你不需要說什麼類型B是。編譯器知道你通過1.0fB == float。有沒有在構造函數調用,以幫助編譯器弄清楚什麼A是的,所以你要告訴它:

Class<int> c(1.0f); 
Class<int>* ptr = new Class<int>(2.0f);