如何制作这个在模板构造函数复制中使用类型定义的类型的模板

How to make this template which using typedefed type in template constructor copmiles?

本文关键字:类型 定义 构造函数 何制作 复制      更新时间:2023-10-16
#include <iostream>
template <typename T>
struct W 
{
    typedef T TT; 
    W(const typename W<int>::TT & m)
    {
        std::cout << "here" << std::endl;
    }
};
int main()
{
    int f;
    W<int>k( f );
    return 0;
}

VC11 可以编译,但 G++ 不起作用。

我的 gcc 版本:

Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=d:/usr/app/mingw-w32/bin/../libexec/gcc/i686-w64-mingw32/4.7 .0/lto-wrapper.exe Target: i686-w64-mingw32 Configured with: ../../../build/gcc/src/configure --target=i686-w64-mingw32 --pr efix=/c/bb/vista64-mingw32/mingw-x86-x86/build/build/root --with-sysroot=/c/bb/v ista64-mingw32/mingw-x86-x86/build/build/root --enable-languages=all,obj-c++ --e nable-fully-dynamic-string --disable-multilib Thread model: win32 gcc version 4.7.0 20111219 (experimental) (GCC)

GCC 错误消息: dd.cc:7:27: error: 'TT' in 'struct W<int>' does not name a type

你不能那样做。

为了知道typename W<int>::TT是什么类型,编译器必须实例化W<int>,但它不能在已经实例化W<int>的情况下执行此操作,因为类型在声明构造函数时不完整。

完整类型与其构造函数之间存在循环依赖关系。

Clang给出了一个有用的错误:

t.cc:7:22: error: implicit instantiation of template 'W<int>' within its own definition
    W(const typename W<int>::TT & m)
                     ^

不确定它是如何在 VC++ 中编译的

但是以下编译与 MinGW g++ 4.7.2

 #include <iostream>
template <typename T>
struct W 
{
   typedef T TT; 
    W(const TT & m) // remove typename W<int> or use  W(const  W::TT & m)
    {
        std::cout << "here" << std::endl;
    }
};
int main()
{
    int f;
    W<int> k( f );
    return 0;
}