gpt4 book ai didi

c++11: 委托(delegate)构造函数 - 无法选择构造函数模板?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:34:58 25 4
gpt4 key购买 nike

这是后续问题:
c++11 dedicated "proxy constructors" delegating to private univeral reference constructor?

我想去掉那里使用的“enum class Dummy”。

但我没有设法委托(delegate)给模板构造函数。
请参见下面的代码示例。

#include <iostream>
#include <string>
#include <typeinfo>

class MyClass
{

private:

template <class T>
MyClass(T&& data)
: _data(std::forward<T>(data))
{
std::cout << "MyClass universal reference template c'tor" << std::endl;
}

public:


// proxy c'tors delegating to universal reference c'tor
MyClass (std::string const & data)
: MyClass<std::string>(data)
{
std::cout << "MyClass lvalue c'tor" << std::endl;
}

MyClass (std::string && data)
: MyClass<std::string>(std::move(data))
{
std::cout << "MyClass rvalue c'tor" << std::endl;
}

private:

std::string _data;

};

int
main(
int,
char**)
{

{
std::string str("demo");
MyClass myClass(str);
}

{
MyClass myClass("hello, world");
}

return 0;
}

我收到以下错误:

main2.cpp: In constructor 'MyClass::MyClass(const string&)':
main2.cpp:21:7: error: 'class MyClass MyClass::MyClass' is not a non-static data member of 'MyClass'
: MyClass<std::string>(data)
^
main2.cpp:21:14: error: expected '(' before '<' token
: MyClass<std::string>(data)
^
main2.cpp:21:14: error: expected '{' before '<' token
main2.cpp: In constructor 'MyClass::MyClass(std::__cxx11::string&&)':
main2.cpp:27:7: error: 'class MyClass MyClass::MyClass' is not a non-static data member of 'MyClass'
: MyClass<std::string>(std::move(data))
^
main2.cpp:27:14: error: expected '(' before '<' token
: MyClass<std::string>(std::move(data))
^
main2.cpp:27:14: error: expected '{' before '<' token
main2.cpp: In function 'int main(int, char**)':
main2.cpp:11:5: error: 'MyClass::MyClass(T&&) [with T = std::__cxx11::basic_string<char>&]' is private
MyClass(T&& data)
^
main2.cpp:46:28: error: within this context
MyClass myClass(str);
^
main2.cpp:11:5: error: 'MyClass::MyClass(T&&) [with T = const char (&)[13]]' is private
MyClass(T&& data)
^
main2.cpp:50:39: error: within this context
MyClass myClass("hello, world");

最佳答案

这并不特定于委派构造函数。构造函数(和转换函数)没有名称,因此在语言中无法为它们提供显式模板参数。引用 C++14,[temp.mem] 14.5.2/5:

[ Note: Because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates. —end note ]

注释不是规范性的,但此注释只是明确说明了第 14 章中规则的后续内容。

关于c++11: 委托(delegate)构造函数 - 无法选择构造函数模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38352691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com