为什么编译器尝试实例化一个我实际上没有在任何地方实例化的模板?
Why does the compiler try to instantiate a template that I don't actually instantiate anywhere?
更新如下
以下是我在main.cpp中的全部代码:
template<class T>
struct other_traits;
template<class T>
struct some_traits{
typedef decltype(&T::operator()) Fty;
typedef typename other_traits<Fty>::type type;
};
int main(){
}
但是,当g++编译得很好时,我在Visual Studio 2010中遇到了以下错误:
src\main.cpp(9):错误C2146:语法错误:缺少";"在标识符"type"之前
--src\main.cpp(10):请参阅对正在编译的类模板实例化"some_traits<T>
"的引用
src\main.cpp(9):错误C2868:"some_traits<T>::type
":使用声明的语法非法;预期合格名称
(我喜欢最后一个,总重量。)
我可以把它看作VC10中的一个错误吗?或者有什么好的理由提前实例化吗?或者是decltype
的错误导致编译器认为Fty
不是依赖名称?
更新:我试图欺骗编译器,认为Fty
是一个使用基类从继承的依赖名称
template<class T>
struct other_traits;
template<class R, class C>
struct other_traits<R (C::*)()>{
typedef R type;
};
template<class Fty>
struct base_traits{
typedef typename other_traits<Fty>::type type;
};
template<class T>
struct some_traits
: public base_traits<decltype(&T::operator())>
{};
但编译器仍然试图当场实例化/编译所有内容,并抛出以下错误:
srcmain.cpp(13): error C2039: 'type' : is not a member of 'other_traits<T>'
with
[
T=
]
srcmain.cpp(19) : see reference to class template instantiation 'base_traits<Fty>' being compiled
with
[
Fty=
]
srcmain.cpp(19) : see reference to class template instantiation 'some_traits<T>' being compiled
srcmain.cpp(13): error C2146: syntax error : missing ';' before identifier 'type'
srcmain.cpp(13): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
srcmain.cpp(13): error C2602: 'base_traits<Fty>::type' is not a member of a base class of 'base_traits<Fty>'
with
[
Fty=
]
srcmain.cpp(13) : see declaration of 'base_traits<Fty>::type'
with
[
Fty=
]
srcmain.cpp(13): error C2868: 'base_traits<Fty>::type' : illegal syntax for using-declaration; expected qualified-name
with
[
Fty=
]
请注意,模板参数为空。有什么想法吗?
这似乎是一个错误(如果没有下面提到的特殊标志集)。以下是Oracle网站上C++模板的摘录:
7.2.2
ISO C++标准允许开发人员编写模板类并非所有成员具有给定模板的合法论点只要违法成员未实例化这个程序仍然很完善。ISOC++标准库使用此技巧然而-template=wholeclass选项实例化所有成员,因此不能与此类模板一起使用类,当使用有问题的模板参数。
当编译器看到decltype
D_4您在这里做了一个假设,这在技术上是不正确的。让我们先解决这个问题。
您假设语法错误意味着模板被实例化。这不是编译模板的方式。模板在实例化之前首先进行编译。这是查找非依赖名称的阶段。在这个阶段肯定会发现语法错误。例如,无论模板参数如何,任何必须是声明的内容都必须以;
结尾。
现在正确的问题是编译器在考虑other_traits<T>
的专业化时是否正确。当然,第9行没有这样的专业化,尽管稍后可能会有专业化。但实例化的相关点是什么呢?我必须查一下(对不起,AFS Away From Standardother_traits<T>将是第9行,然后没有专门化,other_traits<Fty>::type
无效。如果other_traits<Fty>::type
的实例化点与some_traits<T>
的实例化点相同,即没有,那么other_traits<Fty>::type
应该在第1阶段被接受。
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 检查某些类型是否是模板类 std::optional 的实例化
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 模板化类构造函数的模板实例化
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 受约束的成员函数和显式模板实例化
- 对显式实例化的模板函数的未定义引用
- [temp.variadic]中关于包扩展实例化的措辞