[英]Deduce template parameter of class
有人可以幫我理解為什么以下代碼無法編譯的原因:
#include <type_traits>
template< typename T >
class A
{};
template< typename T >
class B
{};
template< template <typename T> class GENERAL_t, // Note: GENERAL_t is either A<T> or B<T>
typename = std::enable_if_t< std::is_same<T,int>::value >
>
void foo( GENERAL_t a )
{}
錯誤信息:
t.cpp:67:57: error: use of undeclared identifier 'T'
typename = std::enable_if_t< std::is_same<T,int>::value >
^
t.cpp:67:65: error: no type named 'value' in the global namespace
typename = std::enable_if_t< std::is_same<T,int>::value >
~~^
t.cpp:69:15: error: use of class template 'GENERAL_t' requires template arguments
void foo( GENERAL_t a )
^
t.cpp:66:43: note: template is declared here
template< template <typename T> class GENERAL_t, // Note: GENERAL_t is either A<T> or B<T>
~~~~~~~~~~~~~~~~~~~~~ ^
3 errors generated.
在此, foo
應該采用class A
或class B
實例,但僅當A
或B
的模板參數T
為int
時才如此。
您尚未聲明T
它必須是模板參數。
將T
放入template <class T> class GENERAL_t
GENERAL_t
是模板模板,因此需要模板參數。
請不要將ALL_CAPS用於宏以外的任何內容
這是工作代碼:
template<class T, template <class> class General_t,
class = std::enable_if_t< std::is_same<T,int>::value >
>
void foo(General_t<T> a)
{}
bolov的回答在所有方面都是正確的。
但是在這種情況下,您不需要在is_same
上使用SFINAE。 您可以僅在template-template上進行模板處理:
template <template <class> class General>
void foo(General<int> ) { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.