2012-08-03 74 views
2

我有一個功能模板,必須只允許某些類型。我見過其他問題,但他們使用boost和primitve類型。在這種情況下,沒有提升,並且它是用戶定義的類。功能模板,不允許某些類型

例:

template<typename T> 
myfunc(T&) 
{ ... } 

template<> 
myfunc(Foo&) 
{ 
    static_assert(false, "You cannot use myfunc with Foo"); 
} 

問題是static_assert獲取不管我是否調用myfuncFoo對象或不叫。

我只是想要一些編譯停止myfuncFoo調用的方式。
如何實現此功能?

+0

['std :: enable_if'](http://en.cppreference.com/w/cpp/types/enable_if) – 2012-08-03 16:03:37

+2

你的函數沒有返回類型... – 2012-08-03 16:04:28

回答

4

您可以使用std::is_same此:

#include <type_traits> 

template<typename T> 
return_type myfunc(T&) 
{ 
    static_assert(std::is_same<T, Foo>::value, "You cannot use myfunc with Foo"); 

    // ... 
} 
+0

雖然我會'std :: remove_const '。 http://ideone.com/ebuud或者'std :: decay'它。 – Xeo 2012-08-03 16:10:43

+1

@Xeo是的,我考慮過這個,但決定採用與原文相同的行爲。我可能會使用'裸':P – 2012-08-03 16:11:35

+0

什麼是'裸'?一個鏈接就夠了。 – 2012-08-03 17:47:36

1

而返回類型R,說:

#include <type_traits> 

template <typename T> 
typename std::enable_if<!std::is_same<T, Foo>::value, R>::type my_func(T &) 
{ 
    // ... 
} 

如果你真的不想使用標準庫,你可以寫性狀:

template <bool, typename> struct enable_if { }; 
template <typename T> struct enable_if<true, T> { typedef T type; }; 

template <typename, typename> struct is_same { static const bool value = false; }; 
template <typename T> struct is_same<T, T> { static const bool value = true; }; 
+0

由於沒有實際的重載被選中,所以靜態斷言更好,因爲它提供了更好的錯誤。 – 2012-08-03 16:06:40

+0

@ R.MartinhoFernandes:是的,也許... – 2012-08-03 16:07:14

+0

@ R.MartinhoFernandes一個永遠不會知道。 ADL將收集「my_func」作者甚至沒有想到的東西。 – 2012-08-03 16:52:14