请考虑以下代码:
template < typename T >
struct A
{
struct B { };
};
template < typename T >
void f( typename A<T>::B ) { }
int main()
{
A<int>::B x;
f( x ); // fails for gcc-4.1.2
f<int>( x ); // passes
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以这里gcc-4.1.2要求f明确指定模板参数.这符合标准吗?较新版本的GCC是否修复了此问题?如何避免int在调用时明确指定f?
更新: 这是一个解决方法.
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
template < typename T >
struct A
{
typedef T argument;
struct B { typedef A outer; };
};
template < …Run Code Online (Sandbox Code Playgroud) 在如下所示的模板中,我希望调用Run(&Base::foo)成功,而无需将Base类型命名两次(如编译Run<Base>(&Base::foo)调用中所做的那样).我可以吗?可能没有添加大量的Boost标头?
使用提供的代码,我得到一个错误:
prog.cpp:26: error: no matching function for call to ‘Run(bool (Base::*)())’
Run Code Online (Sandbox Code Playgroud)
(你可以在http://ideone.com/8NZkq上摆弄这个片段):
#include <iostream>
class Base {
public:
bool foo() { return true; }
};
Base* x;
template<typename T>
struct Traits {
typedef bool (T::*BoolMethodPtr)();
};
template<typename T>
void Run(typename Traits<T>::BoolMethodPtr check) {
T* y = dynamic_cast<T*>(x);
std::cout << (y->*check)();
}
int main() {
Base y;
x = &y;
Run<Base>(&Base::foo);
Run(&Base::foo); // why error?
}
Run Code Online (Sandbox Code Playgroud)