c++ - 模板和 decltype 中不完整类型的无效使用

标签 c++ templates gcc decltype

我需要做以下工作。

这是我实际代码的简化版本,但基本上难度是相同的,即推导工厂方法的返回类型。

具体来说,我需要 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/

相关文章:

c++ - 为模板化 key 专门化 std::hash

十进制转二进制的C程序

fprintf() 的跨平台宏包装器

c - 析构函数在 elf 文件中的位置 : not where it should be?

c++ - 模板参数推断失败

c++ - 在C++中的递归函数中返回

c++ - 如何检查类是否具有默认构造函数,公共(public)的、 protected 或私有(private)的

c++ - getchar 或 cin.get() 在开发 cpp 中不起作用

c++ - decltype 与具有默认参数的函数模板会产生困惑的结果(一个有趣的问题或 gcc 的错误)

c++ - 如何有条件地在具有相同签名的两个构造函数之间切换?