2012-01-12 12 views
0

我想創建一個類模板,ptrs_and_refs_only<T>,它只能通過指針和引用進行操作。換句話說,這種類型的值應該被禁止,除了聲明爲friend s類型的東西。如何確保某個類型的值只能由其朋友操作?

具體來說,我想編譯器發出一個錯誤,如果遇到這種類型作爲函數參數:

void foo(ptrs_and_refs_only<int> x); // error! 
void bar(ptrs_and_refs_only<int> &x); // ok 
void baz(ptrs_and_refs_only<int> *x); // ok 

我知道,我可以讓ptrs_and_refs_only<T>的拷貝構造函數private,但沒有按在此代碼中似乎不會導致錯誤:

template<typename T> 
    class ptrs_and_refs_only 
{ 
    private: 
    ptrs_and_refs_only() {} 
    ptrs_and_refs_only(const ptrs_and_refs_only &) {} 
}; 

void foo(ptrs_and_refs_only<int> x) {} 

int main() 
{ 
    return 0; 
} 

此行爲是否可行?

+4

該代碼不會導致錯誤,但我不認爲你可以從'main'調用'foo'而不會導致編譯器錯誤。 – 2012-01-12 01:41:43

+0

@OliCharlesworth同意。不過,如果我可以禁止'''foo''的存在,那會很好。 – 2012-01-12 01:46:15

+0

那麼,一個純粹的'虛擬'函數將不允許這個'foo',但是..你根本無法實例化那個類。 :) – Xeo 2012-01-12 01:48:37

回答

1

這裏是一個骨架,但我不知道這是否會適應你的需要:

#include <type_traits> 

template <typename T> 
struct notype 
{ 
private: 
    typename std::enable_if<std::is_constructible<notype<T>, T const &>::value, 
          void>::type dummy(); 
    notype(T &) { } 
}; 

void foo(notype<int>) { } // Error 
void foo(notype<int> &) { } 
void foo(notype<int> *) { } 

你還是會需要找到一種方法,使某些客戶端類的類constructible 。

+0

有趣。它爲什麼有效? – 2012-01-12 19:37:31

+0

@JaredHoberock:私有構造函數阻止類從'T const&'構造,所以'enable_if'失敗,您不能實例化模板。其實我不知道它是否會像這樣有用,你可能需要一些調整,以使它可以被* something *構造出來...... – 2012-01-12 19:53:13

+0

我明白那個部分,但爲什麼不'''不是類型 &'''和'''nottype *'''還會實例化模板並導致錯誤? – 2012-01-12 22:53:39