我有一个模板类 item
存储各种类型的对象T
.它还在实例化/初始化中将属性附加到这些对象。
我想要实现的一件特别的事情是每当item
看到 const char *
, 它认为并将其存储为 std::string
.这可以按如下方式完成。
但是在类型检查中,我发现了一个 item
从 const char *
实例化在类型上仍然与 item
不同从 std::string
实例化.请看最后一行的评论 false
,我想制作 true
.
#include <iostream>
#include <string>
#include <type_traits>
using namespace std;
template<typename T>
using bar = typename std::conditional<std::is_same<T, const char *>::value,
string, T>::type;
template<typename T>
class item
{
bar<T> thing;
// other attributes ...
public:
item(T t) : thing(t) {}
// other constructors ...
bar<T> what() const
{
return thing;
}
};
int main()
{
auto a = item("const char *"); // class template argument deduction (C++17)
auto b = item(string("string")); // class template argument deduction (C++17)
cout << std::boolalpha;
cout << (typeid(a.what()) == typeid(b.what())) << endl; // true
cout << (typeid(a) == typeid(b)) << endl; // false
}
我的问题是:是否可以对模板类进行任何更改 item
这样一个item
从 const char *
实例化与 item
的类型相同从 std::string
实例化?
换句话说,我可以对模板类的设计进行任何更改吗 item
这样typeid(a) == typeid(b)
计算结果为真?
谢谢!
注意:这是在之前的 question 之后关于模板功能。但我认为有一些本质上不同的东西值得一个独立的问题。
编辑:我的目标是更改模板类的设计 item
(例如 item
签名),而不是 main
中的代码, 假定由用户提供。我想让 item
的用户生活更轻松,不要求他们明确提供类型 T
在实例化中。这意味着通过 C++17 模板类参数推导或一些等效的解决方法来完成。
更新:谢谢大家!特别感谢@xskxzr,他的一句话完全解决了我的问题。用user-defined deduction guides对于类模板参数推导,我什至不需要 bar<T>
我以前的代码中的技术。我在下面放了更新的代码供您比较。
#include <iostream>
#include <string>
using namespace std;
template<typename T>
class item
{
// UPDATE: no bar<T> needed any more
T thing;
// other attributes ...
public:
item(T t) : thing(t) {}
// other constructors ...
// UPDATE: no bar<T> needed any more
T what() const
{
return thing;
}
};
item(const char *) -> item<std::string>; // UPDATE: user-defined deduction guide !
int main()
{
auto a = item("const char *"); // class template argument deduction (C++17)
auto b = item(string("string")); // class template argument deduction (C++17)
cout << std::boolalpha;
cout << (typeid(a.what()) == typeid(b.what())) << endl; // true
cout << (typeid(a) == typeid(b)) << endl; // UPDATE: now true !
}
最佳答案
您可以添加 user-defined deduction guide :
item(const char *) -> item<std::string>;
有了这个推导指南,a
将被推断为 item<std::string>
.
关于c++ - 类模板实例化中的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240679/