我得到了以下模板(其中包含一个大错误):
template <class FluxVar = IloIntVar, class FluxVarArray = IloIntVarArray,
class DelayVar = IloIntVar, class DelayVarArray = IloIntVarArray,
class LoadVar = IloIntVar, class LoadVarArray = IloIntVarArray,
class BoolVar = IloBoolVar, class BoolVarArray = IloBoolVarArray>
class MyClass {
public:
int getAlpha () { return m_alpha ; }
private:
int m_alpha1 ; // See the "1" here
}
在我的代码中,我做了类似的事情:
MyClass <> myClass1 ;
MyClass <IloNumVar, IloNumVarArray, IloNumVar, IloNumVarArray, IloNumVar, IloNumVarArray> myClass2 ;
MyClass <IloNumVar, IloNumVarArray, IloNumVar, IloNumVarArray, IloNumVar, IloNumVarArray, IloNumVar, IloNumVarArray> myClass3 ;
/* Some stuff with my class BUT NEVER CALL TO myClassX.getAlpha() */
上面的代码使用 MSVC 编译但不使用 GCC,说(当然):
MyClass.h:109:39: error: m_alpha was not declared in this scope
所以我的问题是:标准对此有何规定?这是来自 MSVC 的优化吗?如果是,在这种情况下优化了什么?
我假设 MSVC 不会生成 getAlpha
的代码,因为它从未被调用过,但与 MSVC 一样,我认为这不是标准行为。
最佳答案
据我所知,MSVC 并不总是合规的,并且作为扩展,它允许对类内的成员函数进行专门化。
MSVC 在没有明确告知时不会生成代码。如果您使用该函数成员,它将触发错误,如果您显式专门化它或显式实例化它也是如此:
template <typename T>
class MyClass {
public:
int getAlpha () { return m_alpha32 ; }
private:
int m_alpha1 ; // See the "1" here
};
template<> class MyClass<int>{ // Explicit specialization triggers the error
public:
int getAlpha () { return m_alpha32 ; }
private:
int m_alpha1 ; // See the "1" here
};
template class MyClass<int>; // Explicit instantiation, triggers the error
int main(){
MyClass<int> obj; // doesn't trigger the error alone
obj.getAlpha(); // trigger the error
return 0;
}
另请看这里:http://msdn.microsoft.com/en-us/library/7y5ca42y(v=vs.110).aspx
The compiler generates code for a template class or function when the class or function is instantiated. A member function is instantiated when it is called, and a virtual member function is instantiated when its class is constructed. This can cause problems if you are building a library with templates for other users.
还有
A class template is first specialized and then instantiated by the compiler.
因此,要么不需要诊断,要么根本不生成代码。
关于c++ - 模板实例化错误,MSVC 与 GCC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23492004/