我需要做以下工作。
这是我实际代码的简化版本,但基本上难度是相同的,即推导工厂方法的返回类型。
具体来说,我需要 DeduceObjectT
的第二个或第三个变体(均已注释),而不是第一个,后者需要 FactoryT::ObjectT
typedef。
#include <string>
#include <utility>
#include <memory>
template<class FactoryT>
using DeduceObjectT = typename FactoryT::ObjectT;
//template<class FactoryT>
//using DeduceObjectT = typename decltype(std::declval<FactoryT>().create())::element_type;
//template<class FactoryT>
//using DeduceObjectT = typename std::result_of<decltype(&FactoryT::create)(FactoryT)>::type::element_type;
template<class FactoryT>
struct FactoryUser
{
typedef DeduceObjectT<FactoryT> ObjectT;
};
template<class FactoryUserT>
struct Foo
{
typedef typename FactoryUserT::ObjectT ObjectT;
};
struct StringFactory
{
typedef std::string ObjectT; // want to omit this
std::unique_ptr<std::string> create()
{
return nullptr;
}
Foo<FactoryUser<StringFactory>> t;
};
int main()
{
StringFactory f;
return 0;
}
经过多次尝试,我仍然收到“错误:无效使用不完整类型‘struct StringFactory’”。
我还尝试通过 FactoryUser
的默认模板参数来推导类型。
我真的不明白,考虑到触发所有模板实例化的点位于末尾——声明数据成员t
的行,为什么我会收到错误。
编译器是gcc 4.7.3。与 -std=c++0x -O0
最佳答案
尝试这样的事情:
template <typename Factory>
struct ProductTypedef
{
typedef typename decltype(std::declval<Factory>().create())::element_type ObjectT;
};
struct StringFactory : public ProductTypedef<StringFactory> // CRTP
{
std::unique_ptr<std::string> create()
{
return nullptr;
}
};
关于c++ - 模板和 decltype 中不完整类型的无效使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25292125/