2013-06-20 41 views
3

我想創建只能用作完整類型的類型,而不能用作成員變量類型。如何防止類型被用作struct/class中的成員變量類型?

所以這應允許這種T類型:

T a; 
^^^ 
int foo(T b); 
     ^^^ 
struct C { int foo(T b); }; 
        ^^^ 
int main() { T c; } 
      ^^^ 

但是,這將引起編譯時錯誤:

struct C { T a; }; 
      ^^^ 

我很想呈現什麼我試過到目前爲止,但沒有什麼東西可以至少接近我需要的解決方案,對此抱歉。

當然,我也接受答案,證明這在C++中是不可能的。

爲什麼我需要這個?我想有smart pointer這不能是另一個對象的元素。防止循環依賴的一種可憐的方法...

回答

2

你不能。從C++語法(重點是我的,不相關的部分,爲了清楚起見省略了),用於一個函數的聲明是:

function-definition:
decl-specifier-seqoptdeclarator ctor-initializeropt function-body
decl-specifier-seqoptdeclarator function-try-block

對於一類,它是:

class-specifier:
class-head { member-specificationopt }

member-specification:
member-declaration member-specificationopt
access-specifier : member-specificationopt

member-declaration:
decl-specifier-seqopt member-declarator-listopt ;
function-definition ;opt
::opt nested-name-specifier templateopt unqualified-id ;
using-declaration
template-declaration
member-declarator-list:
member-declarator
member-declarator-list , member-declarator

member-declarator:
declarator pure-specifieropt
declarator constant-initializeropt
identifieropt : constant-expression

最後declarator是:

declarator:
direct-declarator
ptr-operator declarator

direct-declarator:
declarator-id
direct-declarator (parameter-declaration-clause) cv-qualifier-seqopt
exception-specificationopt
direct-declarator [ constant-expressionopt ]
(declarator)

當你CA n看到可以用於函數參數的類型也可以用作類成員。

+0

+!爲你的努力。不過,無論如何,我懷疑這對我有幫助。 – PiotrNycz

+0

@PiotrNycz LOL它只是意味着(從語法的角度來看)可以用作參數的函數**總是可以作爲類成員使用**(除了修飾符)。這意味着您不能阻止某個方法將其參數之一存儲爲類成員。 **即使您重寫賦值運算符**,它們也可以繞過任何使用指針,別名和強制轉換的類型檢查。你可以控制一個對象的創建方式(例如使用工廠方法),但僅此而已(並且它不會阻止對象將循環引用存儲到自身**中)。 –

+0

關於指針的好處,謝謝。 – PiotrNycz

2

如果您可以使用類之外的對象,它可以是類的成員。我99.9%肯定你不能以任何方式阻止它(這並不限制你如何/以何種方式在其他方面使用T--顯然有一個私有構造函數會阻止它成爲一個類的直接成員,但它也會限制它在您顯示的其他三種場景中使用)。

+0

+!爲私人構造的想法。我會嘗試遵循這個概念。 – PiotrNycz