【发布时间】:2019-10-17 13:33:44
【问题描述】:
我在现实世界的应用程序中使用 CRTP 来构建或多或少的大类“堆栈”。我需要知道这些类的“公共基础”是什么,所以我在“堆栈”的一个类中定义了type 和using。后来我不想使用这个定义的类型作为模板函数参数,但这不起作用,我总是遇到“无法用 g++ 推导出模板参数'VAR_TYPE'”。
是否有机会解决这个问题,因为不建议手动定义类型,因为如果我的“类堆栈”的结构发生变化,应该可以自动更改。
template < typename T> struct B { using HERE = B<T>; };
template < typename T> struct C: public B<T> { };
template <typename T>
using COMMON_BASE = typename C<T>::HERE;
template < typename T>
void Print2( )
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
// g++ reports:
// error: no matching function for call to 'CheckMe(COMMON_BASE<int>*&)'
// note: candidate: 'template<class VAR_TYPE> void CheckMe(COMMON_BASE<VAR_TYPE>*)'
// note: template argument deduction/substitution failed:
// note: couldn't deduce template parameter 'VAR_TYPE'
template < typename VAR_TYPE >
void CheckMe( COMMON_BASE<VAR_TYPE>* ) { std::cout << "COMMON_BASE<>" << std::endl; }
// "hardcoded" works fine but should be avoided
//template < typename VAR_TYPE >
//void CheckMe( B<VAR_TYPE>* ) { std::cout << "B<>" << std::endl; }
void CheckMe( int* ) { std::cout << "int" << std::endl; }
//void CheckMe( ... ){ std::cout << "default" << std::endl; }
int main()
{
COMMON_BASE< int >* cb;
B<int>* bi;
CheckMe( cb );
CheckMe( bi );
Print2< COMMON_BASE<int>* >(); // gives: void Print2() [with T = B<int>*]
}
【问题讨论】: