【发布时间】:2019-09-05 14:06:45
【问题描述】:
我正在尝试使用默认原始指针作为默认模板参数。我读到非类型模板参数仅限于整数类型、枚举、指针和引用。使用引用我没有问题,但是当我尝试使用指针时,我遇到了这样的错误:
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;
}
我现在看到的唯一限制是第二个模板参数需要具有静态存储持续时间和外部或内部链接,但代码符合这些要求。感谢任何帮助。
【问题讨论】:
-
No
engine.get()未声明返回常量。 -
@Jean-BaptisteYunès 即使它是,它仍然不会使它成为一个常量表达式。
-
@SergeyA 确定但没有被标记为它不应该被视为的标志。你说得对,我的意思是 constexpr。