c – 嵌套命名空间中模板类的前向声明:默认模板参数应该放在哪
我在嵌套命名空间中有一个模板类的前向声明
namespace n1 { namespace n2 { template <typename T,typename S> struct A; } using n2::A; } 后跟一个定义,实际上是在一个不同的文件中,其间有东西: struct X { }; namespace n1 { namespace n2 { template <typename T,typename S = X> struct A { }; } using n2::A; } 然后以下总是好的: n1::n2::A <int> a; 但这个捷径 n1::A <int> a; 在clang中给出编译错误 error: too few template arguments for class template 'A' 除非我删除了前瞻性声明; g接受两者. clang似乎与第一个不包含默认模板参数的声明保持一致(我不能包含它,因为我还没有定义X). 如果我使用单个命名空间没有问题(但这不是一个解决方案). 我做错了什么,或者哪个编译器是正确的?快捷方式如何与前向声明和嵌套命名空间一起工作?我需要他们所有人. S的前向声明X默认参数当然有效,但实际上太繁琐(实际上有几十个,整个文件结构都会改变). 解决方法
模板< class T>使用myname = some :: templatething< T>;
然后你可以使用myname 在你的情况下,坚持模板< class T,class S = X>使用A = n2 :: A< T,S> ;;在你的n1 刚写了一篇关于这个Symbol not found when using template defined in a library的答案的宝石有btw,有一个阅读. 好吧,它没有被勾选,所以我会帮助更多! 不会编译 #include <iostream> namespace n1 { namespace n2 { template<class U,class V> struct A; } template<class U,class V> using A = n2::A<U,V>; } static n1::A<int,int>* test; struct X {}; namespace n1 { namespace n2 { template<class U,class V> struct A {}; } template<class U,class V=X> using A = n2::A<U,V>; } static n1::A<int> test2; int main(int,char**) { return 0; } 为什么? C的“第一宣言规则” 这是编译器的输出: make all if ! g++ -Isrc -Wall -Wextra -O3 -std=c++11 -g -gdwarf-2 -Wno-write-strings -MM src/main.cpp >> build/main.o.d ; then rm build/main.o.d ; exit 1 ; fi g++ -Wall -Wextra -O3 -std=c++11 -g -gdwarf-2 -Wno-write-strings -Isrc -c src/main.cpp -o build/main.o src/main.cpp:26:17: error: wrong number of template arguments (1,should be 2) static n1::A<int> test2; ^ src/main.cpp:13:47: error: provided for ‘template<class U,class V> using A = n1::n2::A<U,V>’ template<class U,V>; ^ src/main.cpp:26:24: error: invalid type in declaration before ‘;’ token static n1::A<int> test2; ^ src/main.cpp:16:24: warning: ‘test’ defined but not used [-Wunused-variable] static n1::A<int,int>* test; ^ src/main.cpp:26:19: warning: ‘test2’ defined but not used [-Wunused-variable] static n1::A<int> test2; ^ make: *** [build/main.o] Error 好吧,它对未使用的变量抱怨,公平,但注意它是对第13行的引用,那是因为它使用了第一个定义默认模板参数非常原始,我现在不能引用规范. 这可能会提供一些见解. 无论如何注意到: 这编译 #include <iostream> namespace n1 { namespace n2 { template<class U,class V=X> using B = n2::A<U,V>; } static n1::B<int> test2; int main(int,char**) { return 0; } 因为B没有先前的定义. 构建输出 make all if ! g++ -Isrc -Wall -Wextra -O3 -std=c++11 -g -gdwarf-2 -Wno-write-strings -MM src/main.cpp >> build/main.o.d ; then rm build/main.o.d ; exit 1 ; fi g++ -Wall -Wextra -O3 -std=c++11 -g -gdwarf-2 -Wno-write-strings -Isrc -c src/main.cpp -o build/main.o src/main.cpp:16:24: warning: ‘test’ defined but not used [-Wunused-variable] static n1::A<int,int>* test; ^ src/main.cpp:26:19: warning: ‘test2’ defined but not used [-Wunused-variable] static n1::B<int> test2; ^ g++ build/main.o -o a.out 看,好:) 请记住,使用前向声明,您只能使用* s和& s(因为它们具有已知大小,固定大小) – 哦和&& s 所以你需要立即在那里获得默认值! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |