[英]Can I make the constructor of a derived class constexpr if the base class constructor is not constexpr?
[英]Can I pass a lambda to a constexpr constructor?
我有這個 constexpr class:
class ParamType {
public:
constexpr ParamType(std::string_view name, std::string_view uuid,
float minVal, float maxVal, float defVal,
std::function<void(float)> onValue) :
kName(name),
kMinVal(minVal),
kMaxVal(maxVal),
kDefVal(defVal),
uuid(uuid){}
constexpr ParamType(const ParamType &other) = delete;
ParamType &operator=(const ParamType &other) = delete;
constexpr ParamType(ParamType &&other) = default;
constexpr ParamType &operator=(ParamType &&other) = delete;
const std::string_view kName;
const std::string_view uuid;
const float kMinVal, kMaxVal, kDefVal;
};
我正在嘗試添加std::function<void(float)> onValue
。 據我了解,lambda 應該可以分配給 constexpr class。 為什么我不能把它放在那里?
它說:
Constexpr constructor's 6th parameter type 'std::function<void (float)>' is not a literal type 'function<void (float)>' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
我想將此 lambda 存儲到ParamType
這與 lambda 無關。 來自 clang 的實際錯誤消息——只是編譯你的 class,甚至沒有嘗試實例化它——是:
'function<void (float)>' 不是字面量,因為它不是聚合並且除了復制或移動構造函數之外沒有 constexpr 構造函數
這幾乎是不言自明的。
如果onValue
可以成為普通的 function 指針,則可以解決此問題。 以下代碼可以正確編譯(但不適用於捕獲 lambda):
#include <string>
class ParamType {
public:
constexpr ParamType(std::string_view name, std::string_view uuid,
float minVal, float maxVal, float defVal,
void (* onValue) (float)) :
kName(name),
kMinVal(minVal),
kMaxVal(maxVal),
kDefVal(defVal),
uuid(uuid) { }
const std::string_view kName;
const float kMinVal, kMaxVal, kDefVal;
const std::string_view uuid;
};
int main()
{
ParamType pt ("name", "uuid", 1.0, 1.0, 1.0, [] (float f) { });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.