2012-04-02 16 views
1

我想弄清楚在C++中是否有任何已知的模式/習慣用法,我在這裏要做的是什麼。類A必須由具有函數的對象組成,該函數的參數也必須是類型A.以下代碼不能編譯,因爲typeid可能不會用於常量表達式中。有什麼建議麼?如何使用帶參數的封閉類的方法獲得C++對象?

#include <iostream> 
#include <typeinfo> 
using namespace std; 

template <typename T> 
struct B { 
    int f(T& i) { cout << "Hello\n"; } 
}; 

class A { 
    B<typeid(A)> b; 
}; 

int main() 
{ 
    A k; 
} 

回答

0

您正在尋找B<A> b;下面的程序編譯沒有錯誤或G ++ 4.4.3警告。

#include <iostream> 
#include <typeinfo> 
using namespace std; 

template <typename T> 
struct B { 
    int f(T& i) { cout << "Hello\n"; return 0; } 
}; 

class A { 
public: 
    B<A> b; 
}; 

int main() 
{ 
    A k; 
    return k.b.f(k); 
} 

注意:如果您使用的模板,才避免提前聲明,我的解決辦法是錯誤的。但是,如果您出於其他合法理由使用模板,我會將其留在這裏。

1

你們所要求的完全不需要的模板,只是向前聲明:

#include <iostream> 

class A; // forward declare A 

struct B { 
    int f(A &i); // declaration only, definition needs the complete type of A 
}; 

class A { 
    B b; 
}; 

int B::f(A &i) { std::cout << "Hello\n"; } // define f() 

int main() 
{ 
    A k; 
} 
+0

+1 D'oh。 OP根本不需要模板,至少出於他陳述的原因。 – 2012-04-02 19:34:21

相關問題