samedi 27 mai 2023

Different compilation results with template and non-template class having constexpr constructor

A constructor fails to quality as constexpr if the class contains std::vector as its data member since std::vector doesn't have constexpr constructor (atleast until C++17 standards, for C++20 I came across this draft). The issue is if the class itself is templatized, the code successfully gets compiled despite the fact that it has constexpr constructor and std::vector as data member.

Consider following two code snippets:

#include <vector>

class Y {
public:
  constexpr Y(){}
  std::vector<int> v{};
};

int main() {
  Y ob;
  return 0;
}

This code fails to compile whereas the following one compiles successfully

#include <vector>

template<typename T>
class X{
public: 
  constexpr X(){}
  std::vector<T> v;
};

int main() {
  X<int> ob;
  return 0;
}

I do have a slight feel that this might have to do something with how template class is compiled since when I declare a constexpr instance of X constexpr X<int> ob; , it fails to compile but unable to figure out what's actually going under the hood.

Aucun commentaire:

Enregistrer un commentaire