【发布时间】:2017-09-20 10:58:07
【问题描述】:
我有一个问题可以最小化到下面的例子
#include <iostream>
#include <string>
class A{
public:
const char* chr;
A(){chr = "aaa";}
};
class B : A{
public:
const char* chr;
B(){chr = "bbb";}
};
template <class T>
std::string to_str(T) = delete;
template<>
inline std::string
to_str<A>(A object) {
std::string str;
return str.assign((object.chr));
}
int main() {
A a;
B b;
std::cout << to_str(b) << std::endl;
}
将其更改为std::cout << to_str(a) << std::endl; 时,代码运行并打印'aaa',但像这样,它在编译时停止并输出
main.cpp: In function 'int main()':
main.cpp:30:24: error: use of deleted function 'std::__cxx11::string to_str(T) [with T = B; std::__cxx11::string = std::__cxx11::basic_string<char>]'
std::cout << to_str(b) << std::endl;
^
main.cpp:18:13: note: declared here
std::string to_str(T) = delete;
^~~~~~
exit status 1
现在假设我有很多继承 A 的类,我可以“告诉”编译器它们都可以转到同一个函数(接受 A)吗?
谢谢。
【问题讨论】:
-
Java 没有有模板。试图在泛型和模板之间找到一些语法之外的相似之处会造成混淆。
-
您真的需要模板吗?如果没有,那么您只需要 1 个通过 (const) 引用获取
A的常规函数... -
@DsCpp:在课堂上是否必须成为
const char*? -
@DsCpp:您是否可以控制为
to_str编写的专业化? -
B是否必须有一个隐藏A中相同类型成员的成员?您想在to_string中引用哪个?
标签: c++ c++11 templates inheritance