Can't use pointer as a default template parameter

Ole*_*leg 4 c++ templates pointers

I am trying to use default raw pointer as a default template parameter. I read that non type template parameters are restricted to integral types, enums, pointers and references. With references I had no issues, but when I tried to use pointer I am facing such error:

error: non-type template argument of type 'Engine *' is not a constant expression.
Run Code Online (Sandbox Code Playgroud)

Here is my code:

#include <iostream>
#include <memory>

using std::cout;
using std::endl;

class Engine
{
public:
    void startEngine()
    {
        m_started = true;
        cout << "Engine started!" << endl;
    }
private:
    bool m_started = false;
};

template<typename T, T* DEFAULT>
class Car
{
public:
    explicit Car(const uint64_t uid) : m_uid(uid), engine(DEFAULT)
    {
        engine->startEngine();
    }

private:
    uint64_t m_uid;
    T* engine;
};

namespace
{
    std::shared_ptr<Engine> engine = std::make_shared<Engine>();
    Engine* e = engine.get();
}

int main()
{
    Car<Engine, e> lambo(0);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

The only restriction as I see now is that second template argument needs to have static storage duration and external or internal linkage but the code fits these requirements. Appreciate any help.

Joã*_*ulo 5

非类型模板参数必须是一个常量表达式:

非类型模板参数的模板参数应为模板参数类型的转换后的常量表达式(5.20)。


也许您可以解决此问题,使指向的对象具有静态的存储持续时间和链接(请参阅参考资料):

对于指向对象的指针,模板参数必须指定具有静态存储持续时间和链接(内部或外部)或评估为适当的空指针或std :: nullptr_t值的常数表达式的完整对象的地址。

例:

namespace{
    Engine e;
}

int main(){
    Car<Engine, &e> lambo(0);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)