[英]Deduce template parameter of class
Can someone please help me to understand why the following code does not compile: 有人可以帮我理解为什么以下代码无法编译的原因:
#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 )
{}
error message: 错误信息:
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.
Here, foo
should take instances of class A
or class B
but only when the template argument T
of A
or B
is an int
. 在此,
foo
应该采用class A
或class B
实例,但仅当A
或B
的模板参数T
为int
时才如此。
you haven't declared T
. 您尚未声明
T
It needs to be a template parameter. 它必须是模板参数。
drop the T
in the template <class T> class GENERAL_t
将
T
放入template <class T> class GENERAL_t
GENERAL_t
is a template template and as such requires a template parameter. GENERAL_t
是模板模板,因此需要模板参数。
please don't use ALL_CAPS for anything except macros 请不要将ALL_CAPS用于宏以外的任何内容
This is the working code: 这是工作代码:
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's answer is correct in all respects. bolov的回答在所有方面都是正确的。
But in this case, you don't need the SFINAE on is_same
. 但是在这种情况下,您不需要在
is_same
上使用SFINAE。 You can just template on the template-template: 您可以仅在template-template上进行模板处理:
template <template <class> class General>
void foo(General<int> ) { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.