c++ - 不能使用指针作为默认模板参数

标签 c++ pointers templates

我正在尝试使用默认原始指针作为默认模板参数。我读到非类型模板参数仅限于整数类型、枚举、指针和引用。对于引用,我没有遇到任何问题,但是当我尝试使用指针时,我遇到了这样的错误:

error: non-type template argument of type 'Engine *' is not a constant expression.

这是我的代码:

#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;
}

我现在看到的唯一限制是第二个模板参数需要具有静态存储持续时间和外部或内部链接,但代码符合这些要求。感谢任何帮助。

最佳答案

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

A template-argument for a non-type template-parameter shall be a converted constant expression (5.20) of the type of the template-parameter.


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

For pointers to objects, the template arguments have to designate the address of a complete object with static storage duration and a linkage (either internal or external), or a constant expression that evaluates to the appropriate null pointer or std::nullptr_t value.

例子:

namespace{
    Engine e;
}

int main(){
    Car<Engine, &e> lambo(0);
    return 0;
}

关于c++ - 不能使用指针作为默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807312/

相关文章:

c++ - '仅将成员函数添加到类的专用模板

javascript - Meteor.js 如何多次使用同名模板

c++ - 使用 gtest 对 MPI 程序进行单元测试

c++ - 如何创建自己的 ostream/streambuf?

C 将指向 char* 的指针设置为 char*

java - 在java中初始化对象A等于另一个对象B

c++ - 不同 gcc 版本中的结构成员

c++ - MPI C 逐行发送矩阵到所有进程子进程 (MPI_COMM_SPAWN)

c++ - 多速率线程

c - 为什么我可以在一个方法中传递一个指针和 "free"里面的内存?