考虑以下示例:
#include <iostream>
#include <iostream>
#include <type_traits>
template<typename Type, template<typename> class Crtp>
class Base
{
public:
typedef int value;
// f1: OK
// Expected result: casts 4.2 to Base<Type, Crtp>::value
value f1() {return 4.2;}
// f2: NOT OK
// Expected result: casts 4.2 to Crtp<Type>::value
// But f2 does not compile: no type named 'value'
// in 'class Derived<double>'
typename Crtp<Type>::value f2() {return 4.2;}
};
template<typename Type>
class Derived : public Base<Type, Derived>
{
public:
typedef Type value;
};
int main()
{
Derived<double> a;
std::cout<<a.f1()<<std::endl;
std::cout<<a.f2()<<std::endl;
return 0;
}
如何解决这个问题(类Derived
中的 typedef 未知Base
)?
编辑:我发现了一个非常简单的技巧。有人可以向我解释为什么以下内容有效而以前的版本无效吗?这个技巧适用于标准 C++11 还是因为编译器的工作方式(这里是 g++ 4.7.1)而起作用?
#include <iostream>
#include <iostream>
#include <type_traits>
template<typename Type, template<typename> class Crtp>
class Base
{
public:
typedef int value;
value f1() {return 4.2;}
template<typename T = Crtp<Type>> typename T::value f2() {return 4.2;}
};
template<typename Type>
class Derived : public Base<Type, Derived>
{
public:
typedef Type value;
};
int main()
{
Derived<double> a;
std::cout<<a.f1()<<std::endl;
std::cout<<a.f2()<<std::endl;
return 0;
}