2017-11-25 246 views
0

我有一個模板類美孚:C++ - 一個模板類專業函數模板與非類型模板參數

template <class A, A value, class B> 
class Foo {}; 

而且我有一個函數模板validateType()

template <class T> 
bool validateType() { 
    return false; 
} 

現在我想要將它專用於某些類型,包括Foo,以便該函數在編譯期間執行一些static_asserts。我嘗試這樣做:

template <class A, class B, Foo<A, A val, B>> 
bool validateType() { 
    // do some static asserts 
} 

這:

template <class A, A val, class B> 
bool validateType<Foo<A, val, B>>() { 
    // do some static asserts 
} 

在第一個,編譯器說:

error: wrong number of template arguments (2, should be 3) 
template <class A, class B, Foo<A, A val, B>> 
              ^~ 
note: provided for ‘template<class A, A value, class B> class Foo’ 
class Foo {}; 
     ^~~ 
error: two or more data types in declaration of ‘validateType’ 
bool validateType() { 
       ^
error: expected ‘>’ before ‘{’ token 
bool validateType() { 
        ^

而在第二種情況下,我得到

error: non-class, non-variable partial specialization ‘validateType<Foo<A, val, B> >’ is not allowed 
bool validateType<Foo<A, val, B>>() { 
           ^

這應該怎麼做?

回答

1

函數模板不允許使用部分模板特化。
使用SFINAE或類模板

template <class T> 
struct validateType : std::false_type {}; 

template <class A, A val, class B> 
struct validateType<Foo<A, val, B>> : std::true_type {};