我有一个POD类型Foo
我希望用户通过我的用户定义的文字实例化(默认复制,移动和分配都没问题):
struct Foo
{
private:
Foo() = delete;
friend constexpr Foo operator"" _foo (const char* str, std::siz_t n);
const char* var1;
std::size_t var2;
};
constexpr Foo operator"" _foo (const char* str, std::siz_t n)
{
return Foo{str, MyFunc(str, n)};
}
举个例子,我想要这样的东西:
int main()
{
Foo myBar = "Hello, world!"_foo; // ctor via user defined literal OK
Foo myBar2 = myBar; // copy-ctor OK
Foo myBar3 = std::move(myBar2); // move-ctor OK
myBar = myBar3; // assignment OK
Foo myBaz{"Hello, world!", 42}; // ERROR: Must go through the user defined literal
Foo myBaz2; // ERROR: Default ctor not allowed
}
但是使用上面的代码我得到以下编译错误(Xcode 4.6.3 / Clang):
main.cpp:88:12: error: no matching constructor for initialization of '<anonymous>::Foo'
return Foo{str, MyFunc(str, n)};
^ ~~~~~~~~~~~~~~~~~~~~~
main.cpp:60:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
Foo() = delete;
^
main.cpp:57:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
struct Foo
^
main.cpp:57:8: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
如何为业务重新打开{} -ctor,但仅针对用户定义的文字?
答案 0 :(得分:3)
目前您没有双参数构造函数。 Just write one:
struct Foo
{
private:
const char* var1;
std::size_t var2;
friend constexpr Foo operator"" _foo (const char* v, std::size_t len);
constexpr Foo(const char* param1, std::size_t param2) : var1(param1), var2(param2) {}
};